package com.ray.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.DoubleSummaryStatistics;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

import org.apache.commons.lang.math.LongRange;
import org.apache.ibatis.annotations.Case;
import org.apache.ibatis.reflection.wrapper.BaseWrapper;
import org.apache.poi.ss.formula.functions.PPMT;
import org.apache.xmlbeans.impl.jam.mutable.MPackage;
import org.junit.validator.PublicClassValidator;
import org.omg.CosNaming.Binding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.google.appengine.api.search.query.ExpressionParser.name_return;
import com.google.appengine.api.search.query.QueryParser.andOp_return;
import com.google.appengine.repackaged.com.google.storage.onestore.v3.proto2api.OnestoreEntity;
import com.microsoft.schemas.office.visio.x2012.main.VisioDocumentDocument1;
import com.qiniu.streaming.model.StreamListing;
import com.ray.bean.CombinationKeyBean;
import com.ray.bean.CompanyBean;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DeptReachBean;
import com.ray.bean.DisplayViewBean;
import com.ray.bean.DutyBean;
import com.ray.bean.FeedOrderDetailBean;
import com.ray.bean.FeedOrderMainBean;
import com.ray.bean.FeedingAndReportBean;
import com.ray.bean.HalfMaterialBean;
import com.ray.bean.MachingAndColorBean;
import com.ray.bean.MaterialTrunoverBean;
import com.ray.bean.MergeBean;
import com.ray.bean.OrderBean;
import com.ray.bean.OrderCustomTagBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.bean.OtherWarehouseBean;
import com.ray.bean.PersonBean;
import com.ray.bean.ProcedureBean;
import com.ray.bean.ProcessBean;
import com.ray.bean.ProductionExceptionBean;
import com.ray.bean.PutOutOrderBean;
import com.ray.bean.PutOutWarehouseBean;
import com.ray.bean.ReportBean;
import com.ray.bean.TableData;
import com.ray.bean.TurnOverBea;
import com.ray.bean.TurnoverBean;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.bean.WorkshopProductionCycleBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.BasicDataMapper;
import com.ray.mapper.ReportMapper;
import com.ray.mapper.WorkshopMapper;
import com.ray.pojo.MyUser;
import com.ray.util.CreateIdUtil;
import com.ray.util.ExceptionUtil;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.ray.util.TimeAndUnix;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.WeiXinUtil;
import com.ray.util.redis.RedisCache;
import com.ray.util.redis.RedisKey;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

import net.sf.json.JSONArray;

@Service
public class WorkshopService {
	public static Set<String> KUANG_TUI_SET=new HashSet<String>();
	//	public static Set<String> UNIT_SET=new HashSet<String>();
	static {
		KUANG_TUI_SET.add("金属圈");
		KUANG_TUI_SET.add("板材圈");
		KUANG_TUI_SET.add("TR圈");
		KUANG_TUI_SET.add("塑钢圈");
		KUANG_TUI_SET.add("注塑圈");
		KUANG_TUI_SET.add("TLL圈");
		KUANG_TUI_SET.add("金属肶");
		KUANG_TUI_SET.add("板材肶");
		KUANG_TUI_SET.add("TR肶");
		KUANG_TUI_SET.add("PC肶");
		KUANG_TUI_SET.add("塑钢肶");
		KUANG_TUI_SET.add("注塑腿");
		KUANG_TUI_SET.add("TLL肶");

//		UNIT_SET.add("付");
//		UNIT_SET.add("粒");
//		UNIT_SET.add("个");
//		UNIT_SET.add("颗");
//		UNIT_SET.add("支");
	}


	@Autowired
	WorkshopMapper workshopMapper;
	//	@Autowired
//	PutOutMapper putOutMapper;
	@Autowired
	ShenHeService shenHeService;
	@Autowired
	OrderService orderService;
	@Autowired
	ApprovalService approvalService;
	@Autowired
	BasicDataMapper basicDataMapper;
	@Autowired
	BasicDataService basicDataService;
	@Autowired
	CompanyMaterialService companyMaterialService;
	@Autowired
	PutOutServiceNew putOutServiceNew;
	@Autowired
	CompanyService companyService ;
	@Autowired
	OtherWarehouseService otherWarehouseService;
	@Autowired
	WeiXinPeopleService weiXinPeopleService;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	WarehouseService warehouseService;
	@Autowired
	StructureTreeService structureTreeService;
	@Autowired
	UserService userService;
	@Autowired
	ShoppingMallService shoppingMallService;
	@Autowired
	IssueNoteService issueNoteService;
	@Autowired
	EquipmentService equipmentService;
	@Autowired
	ReportMapper reportMapper;

	//获取工序详情
	public List<ProcedureBean> getProcessDetail(String productionLine,String workshop,String procedure) {
		List<ProcedureBean> procedureDetailBean = workshopMapper.getProcessDetail(productionLine,workshop,procedure);
		return procedureDetailBean;
	}

	//获取订单信息
	public List<WorkshopProductionCycleBean> getWorkshopProductionDetail(Map map) throws ServiceException {
		List<WorkshopProductionCycleBean> workshopProductionDetailBean=workshopMapper.getWorkshopProductionDetail(map);
		return workshopProductionDetailBean;
	}

	//获取车间名称
	public List<String> getWorkshopName(Map map) {
		return workshopMapper.getWorkshopName(map);
	}

	//从工序表获取工序名称
	public List<String> getProcessNameFromProcess(){
		return workshopMapper.getProcessNameFromProcess();
	}

	//从车间生产周期表获取生产线名称
	public List<String> getProductionLineFromCycle() {
		return workshopMapper.getProductionLineFromCycle();
	}

	//根据车间名称获取工序名称
	public List<String> getWorkingProcedureName(Map map) {
		return workshopMapper.getWorkingProcedureName(map);
	}

	/**
	 * 通过redis获取产能信息
	 * @param map
	 * @return
	 * @throws ParseException
	 */
	public List<ProductionExceptionBean> queryCapacityFromRedis(Map map) throws ParseException{
		StringUtil.checkIsTrue(map, "month", "未获取到月份");
		String company=map.get("loginCompany").toString();
		String month=map.get("month").toString();
		String capacityRedisKey=RedisKey.COMPANY_WORKSHOP_CAPACITY+company+month;
		List<ProductionExceptionBean> capacityList=(List<ProductionExceptionBean>) RedisCache.getDataFromRedis(capacityRedisKey);
		if(null==capacityList) {
			Map paramMap=new HashMap();
			paramMap.put("loginCompany", map.get("loginCompany"));
			paramMap.put("month", map.get("month"));
			paramMap=this.setCompanyReportIsNeedApproval(paramMap);
			capacityList=this.queryCapacity(paramMap,RedisKey.QUERY_REPORT_CAPACITY);
			if(null==capacityList) {
				capacityList=new ArrayList<ProductionExceptionBean>();
			}
			RedisCache.setDataToRedis(capacityRedisKey, capacityList, RedisKey.COMPANY_WORKSHOP_CAPACITY_EXPIRETIME);
		}
		//如果要过滤部门
		if(null!=map.get("deptId") && !"".equals(map.get("deptId").toString())) {
			capacityList=capacityList.stream().filter(pp->pp.getDeptId().equals(map.get("deptId").toString())).collect(Collectors.toList());
		}
		//如果要过滤车间
		String workShopIdListStr=map.get("workShopIdList")==null?"":map.get("workShopIdList").toString();
		if(!"".equals(workShopIdListStr)) {
			JSONArray jsonArray=JSONArray.fromObject(workShopIdListStr);
			List<String>  workShopIdList = jsonArray.subList(0, jsonArray.size());
			capacityList=capacityList.stream().filter(pp->workShopIdList.contains(pp.getWorkShopId())).collect(Collectors.toList());
		}else if(null!=map.get("workShopId") && !"".equals(map.get("workShopId").toString())) {
			capacityList=capacityList.stream().filter(pp->pp.getWorkShopId().equals(map.get("workShopId").toString())).collect(Collectors.toList());
		}
		return capacityList;
	}


	/**
	 * 从redis中获取车间设备产能信息
	 * @param map
	 * @return
	 * @throws ParseException
	 */
	public List<ProductionExceptionBean> queryMacineCapacityRedis(Map map) throws ParseException{
		StringUtil.checkIsTrue(map, "month", "未获取到月份");
		String company=map.get("loginCompany").toString();
		String month=map.get("month").toString();
		String capacityRedisKey=RedisKey.COMPANY_WORKSHOP_MACHINE_CAPACITY+company+month;
		List<ProductionExceptionBean> capacityList=null;
//		List<ProductionExceptionBean> capacityList=(List<ProductionExceptionBean>) RedisCache.getDataFromRedis(capacityRedisKey);
		if(null==capacityList) {
			Map paramMap=new HashMap();
			paramMap.put("loginCompany", map.get("loginCompany"));
			paramMap.put("month", map.get("month"));
			capacityList=this.queryCapacity(paramMap,RedisKey.QUERY_MACHINE_CAPACITY);
			if(null==capacityList) {
				capacityList=new ArrayList<ProductionExceptionBean>();
			}
			RedisCache.setDataToRedis(capacityRedisKey, capacityList, RedisKey.COMPANY_WORKSHOP_MACHINE_CAPACITY_EXPIRETIME);
		}
		//如果要过滤部门
		if(null!=map.get("deptId") && !"".equals(map.get("deptId").toString())) {
			capacityList=capacityList.stream().filter(pp->pp.getDeptId().equals(map.get("deptId").toString())).collect(Collectors.toList());
		}
		//如果要过滤车间
		String workShopIdListStr=map.get("workShopIdList")==null?"":map.get("workShopIdList").toString();
		if(!"".equals(workShopIdListStr)) {
			JSONArray jsonArray=JSONArray.fromObject(workShopIdListStr);
			List<String>  workShopIdList = jsonArray.subList(0, jsonArray.size());
			capacityList=capacityList.stream().filter(pp->workShopIdList.contains(pp.getWorkShopId())).collect(Collectors.toList());
		}else if(null!=map.get("workShopId") && !"".equals(map.get("workShopId").toString())) {
			capacityList=capacityList.stream().filter(pp->pp.getWorkShopId().equals(map.get("workShopId").toString())).collect(Collectors.toList());
		}
		return capacityList;
	}


	/**
	 *查询产能信息
	 * @param i
	 *
	 */
	public List<ProductionExceptionBean> queryCapacity(Map map, int type) throws ParseException {
		//车间排单产能
		map.put("workShop", map.get("workShopId"));
		map=this.setCompanyReportIsNeedApproval(map);
		List<TurnoverBean> listTurnover=workshopMapper.getWorkShopTurnover(map);
		List<WorkshopProductionCycleBean> workshopPaiList=workshopMapper.getWorkshopPaiList(map);
		List<ProductionExceptionBean> listCapacity=null;
		//查询报工产能
		if(type==RedisKey.QUERY_REPORT_CAPACITY) {
			listCapacity=this.getCapacity(map);
		}
		//查询设备产能
		if(type==RedisKey.QUERY_MACHINE_CAPACITY) {
			listCapacity=equipmentService.getMachineCapacity(map);
		}
		for(WorkshopProductionCycleBean wpcb:workshopPaiList) {
			for(ProductionExceptionBean peb:listCapacity) {
				if(wpcb.getId().equals(peb.getWorkShopId())) {
					peb.setTurnover((long) wpcb.getTuenoverTwo());
					if(type==RedisKey.QUERY_REPORT_CAPACITY) {
						break;
					}
				}
			}
		}
		for(TurnoverBean turnoverBean:listTurnover) {
			for(ProductionExceptionBean peb:listCapacity) {
				if(turnoverBean.getWorkShopId().equals(peb.getWorkShopId())) {
					peb.setWorkShopStartTurnover(turnoverBean.getTurnover());
					if(type==RedisKey.QUERY_REPORT_CAPACITY) {
						break;
					}
				}
			}
		}
		return listCapacity;
	}


	/**
	 * 获取产能
	 * @param map
	 * @return
	 */
	public  List<ProductionExceptionBean> getCapacity(Map map) {
//		List<ProductionExceptionBean> returnList=new ArrayList<ProductionExceptionBean>();
		//未分组合并数据
		List<ProductionExceptionBean> list=workshopMapper.queryCapacity(map);
		for(ProductionExceptionBean pp:list) {
			List<DutyBean> ddList=new ArrayList<DutyBean>();
			Map<String,List<DutyBean>> daySet=pp.getListDuty().stream().collect(Collectors.groupingBy(DutyBean::getDelayTime));
			for(String key:daySet.keySet()) {
				long dayCapacity=0;
				//一天的数据
				List<DutyBean> oneDay=daySet.get(key);
				Map<String,List<DutyBean>> groupOrderId=oneDay.stream().collect(Collectors.groupingBy(DutyBean::getOrderId));
				for(String orderKey:groupOrderId.keySet()) {
					List<DutyBean> oneOrderList=groupOrderId.get(orderKey);
					long fiveCount= oneOrderList.stream().filter(oneOrder->"-1".equals(oneOrder.getRowIndex())).mapToLong(DutyBean::getCapacity).sum();
					long noFiveCount= oneOrderList.stream().filter(oneOrder->!"-1".equals(oneOrder.getRowIndex())).mapToLong(DutyBean::getCapacity).sum();
					dayCapacity=dayCapacity+(fiveCount>noFiveCount?fiveCount:noFiveCount);
				}
				DutyBean dutyBean=new DutyBean();
//		    	for(DutyBean db:oneDay) {
//		    		dayCapacity=dayCapacity+db.getCapacity();
//		    	}
				dutyBean.setDelayTime(key);
				dutyBean.setCapacity(dayCapacity);
				ddList.add(dutyBean);
			}
			pp.setListDuty(ddList);
		}
		return list;
	}

	//空字符串转换为null
	String emptyToNull(String empty) {
		if("".equals(empty))
			empty=null;
		return empty;
	}
	//获取车间人员工作效率
	public DatatablesViewPageBean<TableData> getTableData(Map map) throws ServiceException {
//	    map=this.workShopToId(map);
		String userId = map.get("userId")==null?"":map.get("userId").toString();
		//如果是查询单人工资
		if(!"".equals(userId)) {
			//查看这个人是否是计件，如果不是计件则返回null
			List<PersonBean> list = basicDataService.getPersonDetail(userId);
			if(list.size()<=0||"按月".equals(list.get(0).getMethod())) {
				return null;
			}
		}
		map=this.setCompanyReportIsNeedApproval(map);
		//获取原始数据
		List<TableData> list=workshopMapper.getTableData(map);
		int count=list.size();
		DatatablesViewPageBean<TableData> dtcpb=new DatatablesViewPageBean<TableData>();
		count=workshopMapper.getTableDataCount(map);
		dtcpb.setReturnData(list);
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}


	/**
	 * 设置公司报工是否需要审核
	 * @param map
	 * @return
	 */
	private Map setCompanyReportIsNeedApproval(Map map) {
		CompanyBean companyBean=companyService.getCompany(map);
		if(companyBean.getIsApprovalReport()==1) {
			map.put("isApprovalReport", 1);
		}
		return map;
	}

	/***
	 * 获取人员产能信息
	 * @param workShop(车间id)
	 * @param date(结束时间)
	 * @param startDay(开始时间)
	 * @param searchingWhere(搜索条件)
	 * @return
	 */
	public Map getPersonData(Map map)  {
		Assert.notNull(map.get("workShop"),"未获取到车间");
		Map returnMap=new HashMap();
		map=this.setCompanyReportIsNeedApproval(map);
		List<TableData> list=workshopMapper.getPersonData(map);
		returnMap.put("haveProcedure", list);
		Map<String, List<TableData>> groupBy = list.stream().collect(Collectors.groupingBy(TableData::getName));
		List<TableData> noProcedure=new ArrayList<TableData>();
		for(String key:groupBy.keySet()) {
			TableData xx=new TableData();
			double capacity=0.0;
			double effectiveTime=0.0;
			double workEffective=0.0;
			double sumPrice=0.0;
			for(TableData tt:groupBy.get(key)) {
				capacity=capacity+tt.getCapacity();
				effectiveTime=effectiveTime+tt.getEffectiveTime();
				workEffective=workEffective+tt.getWorkEffective();
				sumPrice=sumPrice+tt.getSumPrice();
			}
			xx.setCapacity(capacity);
			xx.setName(key);
			xx.setEffectiveTime(effectiveTime);
			xx.setWorkEffective(workEffective);
			xx.setSumPrice(sumPrice);
			noProcedure.add(xx);
		}
		returnMap.put("noProcedure", noProcedure);
		return returnMap;
	}

	//获取达成率数据
	public List<DeptReachBean> getTotal(String deptId,String date,String startDay, MyUser myUser) throws ParseException {
		date=date+" 00:00:00.000";
		startDay=startDay+" 00:00:00.000";
		int days=TimeAndUnix.getDateDays(startDay, date)+1;
		return workshopMapper.getTotal(deptId,date,startDay,days,myUser);
	}

	//获取订单尾数信息
	public DatatablesViewPageBean<DutyBean> getDutyDate(Map map) throws ServiceException {
		int count=0;
		DatatablesViewPageBean<DutyBean> dtcpb=new DatatablesViewPageBean<DutyBean>();
		count=workshopMapper.getDutyDateCount(map);
		dtcpb.setReturnData(workshopMapper.getDutyDate(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	public List<DeptReachBean> getDuty(Map map) throws ServiceException {
		return workshopMapper.getDuty(map);
	}

	public List<DeptReachBean> getQualified(Map map) {
		List<DeptReachBean> list=workshopMapper.getQualified(map);
		if(null==list || list.size()<=0) {
			list=this.deptReachNull(map);
		}
		return list;
	}

	public List<DeptReachBean> deptReachNull(Map map){
		List<DeptReachBean> list=new ArrayList<DeptReachBean>();
		List<String> deptList=this.getWorkshopName(map);
		for(String dept:deptList) {
			DeptReachBean deptReachBean=new DeptReachBean();
			deptReachBean.setDeptName(dept);
			deptReachBean.setReach("0.0");
			list.add(deptReachBean);
		}
		return list;
	}

	public DatatablesViewPageBean<DutyBean>  getDelayDate(Map map) {
		int count=0;
		DatatablesViewPageBean<DutyBean> dtcpb=new DatatablesViewPageBean<DutyBean>();
		count=workshopMapper.getDelayDateCount(map);
		dtcpb.setReturnData(workshopMapper.getDelayDate(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	public List<DeptReachBean> getOnTime(Map map) {
		List<DeptReachBean> list=workshopMapper.getOnTime(map);
		if(null==list || list.size()<=0) {
			list=this.deptReachNull(map);
		}
		return list;
	}

	public List<DeptReachBean> getSereven(Map map) {
		return workshopMapper.getSereven(map);
	}

	public List<DutyBean> getSoonDelay(Map map) {
		return workshopMapper.getSoonDelay(map);
	}

	//获取合并车间
	public MergeBean getMergeBean(String workshop) {
		return workshopMapper.getMerge(workshop);
	}

	//修改报工
	public List<ReportBean> updateReport(Map map) throws CloneNotSupportedException {
		String reportArrayJSONStr=map.get("reportArrayJSONStr").toString();
		JSONArray jsonArray = JSONArray.fromObject(reportArrayJSONStr);//把String转换为 数组
		List<ReportBean> list= (List<ReportBean>)JSONArray.toCollection(jsonArray, ReportBean.class);
		List<ReportBean> returnList=new ArrayList<ReportBean>();
		List<ReportBean> updateList=new ArrayList<ReportBean>();
		List<ReportBean> otherList=new ArrayList<ReportBean>();
		CompanyBean companyBean=companyService.getCompany(map);
		for(ReportBean report:list) {
			//获取报工数据
			ReportBean reportBean=this.getOneReportBeanByTypeId(map.get("id").toString());
			orderService.checkOrderIsFinish(reportBean.getOrderId());
			if(reportBean.getStatus()!=2) {
				reportBean.setReturnException(reportBean.getOrderId()+"未退回不可修改");
				returnList.add(reportBean);
				continue;
			}
			reportBean.setIsApprovalReport(companyBean.getIsApprovalReport());
			//获取车间
			WorkshopProductionCycleBean wc=basicDataService.getWCById(reportBean.getWorkShopName());
			//获取车间名称
			String workShop=wc.getWorkshopName();
			//获取该车间交接入库数(合格数)
			MergeBean mergeBean=workshopMapper.getMerge(reportBean.getWorkShopName());
			long inCount=workshopMapper.getOrderTurnoverCount(reportBean);
			if(null==mergeBean) {
				inCount=workshopMapper.getOrderTurnoverCount(reportBean);
			}else {
				workShop=mergeBean.getMergeToWorkShop();
				ReportBean reb=reportBean.clone();
				reb.setWorkShopName(mergeBean.getMergeToWorkShopId());
				inCount=workshopMapper.getOrderTurnoverCount(reb);
			}
//			获取投料数和报工数
			FeedingAndReportBean feedingAndReportBean=new FeedingAndReportBean();
			//获取投料数与报工数
			feedingAndReportBean.setFeddingCount(workshopMapper.getOrderCount(reportBean));//投料数
			//已报工数为报工总和减去之前报工数
			feedingAndReportBean.setReportCount(workshopMapper.getReportCount(reportBean)-reportBean.getQualified()-reportBean.getNoQualified());//报工数减此项报工数
			//获取工序
			ProcessBean processBean=basicDataService.getProcessById(reportBean.getProcedur());
			//如果工序不是交接入库
			if(!processBean.getProcessName().equals("交接入库")) {
				//如果工序是交接出库或者交接至客户，已报工数为出库和减去上次报工数
				if(processBean.getProcessName().equals("交接出库") || processBean.getProcessName().equals("交接至客户")) {
					reportBean.setType(2);
					if(null==mergeBean) {
						inCount=workshopMapper.getOrderTurnoverCount(reportBean);
					}else {
						workShop=mergeBean.getMergeToWorkShop();
						ReportBean reb=reportBean.clone();
						reb.setWorkShopName(mergeBean.getMergeToWorkShopId());
						inCount=workshopMapper.getOrderTurnoverCount(reb);
					}
					feedingAndReportBean.setReportCount(workshopMapper.getOrderOutCount(reportBean)-reportBean.getQualified()-reportBean.getNoQualified());
				}
//				入库数小于0
				if(inCount<=0) {
					reportBean.setReturnException(reportBean.getColor()+"在"+workShop+"车间还没有交接入库");
					returnList.add(reportBean);
					continue;
				}
//				入库数小于修改的报工数
				if(inCount<(report.getQualified()+report.getNoQualified())) {
					reportBean.setReturnException(reportBean.getColor()+"修改数大于"+workShop+"车间入库数"+inCount);
					returnList.add(reportBean);
					continue;
				}
				//报工数大于还可报工数
				if(inCount-feedingAndReportBean.getReportCount()-report.getQualified()-report.getNoQualified()<0) {
					reportBean.setReturnException(reportBean.getColor()+"已报工"+feedingAndReportBean.getReportCount()+"个，最多还可修改"+(inCount-feedingAndReportBean.getReportCount())+"个");
					returnList.add(reportBean);
					continue;
				}
				if(reportBean.getOtherType()==1) {//车间交接
					report.setOtherId(reportBean.getOtherId());
				}else if(reportBean.getOtherType()==2 ||reportBean.getOtherType()==4||reportBean.getOtherType()==5||reportBean.getOtherType()==6||reportBean.getOtherType()==9) {//仓库交接
//					List<WarehouseInOutDetailBean> xx=new ArrayList<WarehouseInOutDetailBean>();
					WarehouseInOutDetailBean warehouseInOutDetailBean=new WarehouseInOutDetailBean();
					warehouseInOutDetailBean.setStatus(0);
					warehouseInOutDetailBean.setId(reportBean.getOtherId());
					//如果单位不一样，进行单位转换
					WarehouseInOutDetailBean  unitBean=workshopMapper.getWarehouseReportUnitById(reportBean.getOtherId());
					Assert.notNull(unitBean,"关联出入库记录错误");
					double count=report.getQualified();
					double noCount=report.getNoQualified();
					if(!"付".equals(unitBean.getInOutUnit())) {
						count=report.getQualified()/(reportBean.getQualified()/unitBean.getCount());
						noCount=report.getNoQualified()/(reportBean.getNoQualified()/unitBean.getCount());
					}
					warehouseInOutDetailBean.setCount(count);
					warehouseInOutDetailBean.setNoCount(noCount);
					warehouseInOutDetailBean.setCompany(map.get("loginCompany").toString());
					warehouseService.updateWarehouseInOutCount(warehouseInOutDetailBean);
//					companyMaterialService.updateWarehouseInOutCount(mm);
				}else if(reportBean.getOtherType()==3){//外协交接
					PutOutWarehouseBean putOut=new PutOutWarehouseBean();
					putOut.setCount(report.getQualified());
					putOut.setNoCount(report.getNoQualified());
					putOut.setStatus(0);
					putOut.setId(reportBean.getOtherId());
					putOut.setUpdateUser(map.get("loginUserId").toString());
					putOutServiceNew.updatePutoutCount(putOut);
				}
				updateList.add(report);
			}else {
				reportBean.setType(1);
//				reportBean.setIsApprovalReport(3);//统计所有，不管审核未审核
				Assert.isTrue(reportBean.getOtherType()==0,"其他车间交接物料只能修改出库数");
				feedingAndReportBean=this.GetOrderSystemCount(reportBean.getOrderId(), reportBean.getMachining(), reportBean.getRowIndex(),reportBean.getMaterialCode());
				feedingAndReportBean.setFeddingCount(workshopMapper.getOrderCount(reportBean));
				//				inCount=workshopMapper.getOrderAllWorkShopTurnoverCount(reportBean);
//				如果是交接入库，入库数减掉此项报工数(如果批量修改，同一订单交接入库数,先一个一个修改)
				if(processBean.getProcessName().equals("交接入库")) {
					inCount=feedingAndReportBean.getWorkShopCount()-reportBean.getQualified()-reportBean.getNoQualified();
					if(inCount<0) {
						inCount=0;
					}
				}
				//如果报工数大于投料数减掉已交接入库数（还可入库数）
				if((report.getQualified()+report.getNoQualified())>(feedingAndReportBean.getFeddingCount()-inCount-feedingAndReportBean.getPutOutCount()-feedingAndReportBean.getFeddingCount())) {
					reportBean.setReturnException(reportBean.getColor()+"有效入库:车间:"+inCount+"、外协:"+feedingAndReportBean.getPutOutCount()+"、成品:"+feedingAndReportBean.getFinishCount()+inCount+",最多还可修改"+(feedingAndReportBean.getFeddingCount()-inCount-feedingAndReportBean.getPutOutCount()-feedingAndReportBean.getFeddingCount())+"个");
					returnList.add(reportBean);
					continue;
				}
				updateList.add(report);
			}
		}
		if(updateList.size()>0) {
			workshopMapper.updateReport(updateList);
		}
		return returnList;
	}

	/**
	 * 获取订单某行物料在车间数目
	 * @param orderId(订单编号)
	 * @param machining (加工对象/物料类型)
	 * @param rowIndex(行号)
	 * @param reportBean
	 * @return
	 */
	public long getOrderAllWorkShopTurnoverCount(ReportBean reportBean) {
		return workshopMapper.getOrderAllWorkShopTurnoverCount(reportBean);
	};
	//报工
	/**
	 * @param reportArrayJSONStr 报工数据
	 * @param reportPerson 申报人  一般为空
	 * @param myUser 登录人
	 * @return
	 * @throws ServiceException
	 * @throws CloneNotSupportedException
	 */
	public String insertReport(String reportArrayJSONStr,String reportPerson,MyUser myUserr) throws ServiceException, CloneNotSupportedException {
		JSONArray jsonArray = JSONArray.fromObject(reportArrayJSONStr);//把String转换为 数组
		List<ReportBean> list= (List<ReportBean>)JSONArray.toCollection(jsonArray, ReportBean.class);
		Map map=new HashMap();
		map.put("loginCompany", myUserr.getCompany());
		//公司配置信息（主要报工是否需要审核）
		CompanyBean companyBean=companyService.getCompany(map);
		//如果公司设置的是,结单后不可以报工
		if(1!=companyBean.getAfterFinishIsCanReport()) {
			orderService.checkOrderIsFinish(list.get(0).getOrderId());
		}
		//如果是设备订单另做处理
		if("设备订单".equals(list.get(0).getOrderType())) {
			return this.equipmentReport(list.get(0),reportPerson,myUserr);
		}


		/**
		 * 如果只退仓库不退车间
		 */
		if(list.get(0).getIsOnlyReturnWarehouse() != null && list.get(0).getIsOnlyReturnWarehouse().equals(1)) {
			return this.reportOnlyReturnWarehouse(list,reportPerson,myUserr);
		}

		List<ReportBean> inList=new ArrayList<ReportBean>();
		//仓库库记录
		List<WarehouseInOutDetailBean> inOutList=new ArrayList<WarehouseInOutDetailBean>();
		//外协记录
		List<PutOutWarehouseBean> putOutOrderList=new ArrayList<PutOutWarehouseBean>();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
		String day=formatter.format(new Date())+" 0:00:00";
		formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
		String dateString="";
		if(null==list.get(0).getTouchTime() || "".equals(list.get(0).getTouchTime())) {
			dateString= formatter.format(new Date());
		}else {
			dateString = list.get(0).getTouchTime();
		}
		String tishi="未审批";
		//订单信息
		OrderBean orderBean=orderService.getOrderByOrderId(list.get(0).getOrderId());
		WorkshopProductionCycleBean wc=basicDataService.getWCById(list.get(0).getWorkShopName());
		WorkshopProductionCycleBean wcin=null;
		String workShop=wc.getWorkshopName();
		//获取车间合并情况
		MergeBean mergeBean=workshopMapper.getMerge(wc.getId());
		if(null!=mergeBean) {
			workShop=mergeBean.getMergeToWorkShop();
		}
		//工序信息
		ProcessBean processBean=basicDataService.getProcessById(list.get(0).getProcedur());
		Assert.isTrue(processBean.getReportMode()==1,"该工序为设备报工方式，不可扫码报工");
		ProcessBean inProcessBean=null;
		//微信提醒信息  工序与工厂型号
		StringBuilder weiXinNeiRong=new StringBuilder("");
		weiXinNeiRong.append("工序名称:").append(processBean.getProcessName()).append("\n")
				.append("订单编号:").append(orderBean.getCompanyOrderId()).append("\n")
				.append("工厂型号:").append(orderBean.getFactoryId()).append("\n");
		//整架map

		Map<String,String> allMap=new HashMap<String,String>();
		//获取该车间交接入库数(一开始是车间入库数减车间出库数)
//		long inCount=0;
		long sort=workshopMapper.getMaxSort()+1;
		//设置typeId
		Map<String,String> rowIndexIdMap=new HashMap<String,String>();
		//订单已经报过功的数据
		List<ReportBean> aleradyReportList=reportMapper.getAleradyReportData(list.get(0).getOrderId());
		List<ReportBean> thisPrcessReportList = aleradyReportList.stream().filter(dd->dd.getProcedur().equals(processBean.getId()) && dd.getIsMachineReport() == 1).collect(Collectors.toList());
		Assert.isTrue(thisPrcessReportList == null || thisPrcessReportList.size()<=0,"该订单改工序已在设备报工");
		if(null==aleradyReportList) {
			aleradyReportList=new ArrayList<ReportBean>();
		}
		//订单明细数据
		List<OrderInfoDetailBean> detailList=reportMapper.getOrderInfoDetailIncludeDianDu(list.get(0).getOrderId());

		//按行号倒序排序
		Collections.sort(list, Comparator.comparing(ReportBean::getRowIndex).reversed());
		int   isFinishWarehouse = 0;//是否是成品仓，1是 0不是
		for(ReportBean reportBean:list) {
			if(reportBean.getQualified()+reportBean.getNoQualified()<=0) {
				throw new ServiceException("合格数加不合格数必须大于0");
			}
			//微信消息提醒微信颜色，合格数，不合格数
			weiXinNeiRong.append("物料:").append(reportBean.getMachining()).append("\n")
					.append("颜色:").append(reportBean.getColor()).append("\n")
					.append("合格数:").append(reportBean.getQualified()).append("\n")
					.append("不合格数:").append(reportBean.getNoQualifiedReason()==null?0:reportBean.getNoQualifiedReason()).append("\n");
			reportBean.setTouchPeople(myUserr.getUserId());
			reportBean.setIsApprovalReport(companyBean.getIsApprovalReport());
			//如果是网页上报工将申报人设为制单人，制单人后传入
			if(!(reportPerson==null||reportPerson.equals(""))) {
				reportBean.setReportPeople(reportBean.getTouchPeople());
				reportBean.setTouchPeople(reportPerson);
			}
			if(reportBean.getColor().equals("无")) {
				throw new ServiceException("请先设置颜色");
			}
			reportBean.setSortKey(sort);
			reportBean.setTime(day);//设置日期时间
			reportBean.setCompany(myUserr.getCompany());
			reportBean.setTouchTime(dateString);
			//如果不是单物料,设置组合id
			if(reportBean.getMachingType()!=0) {
				if("-1".equals(reportBean.getRowIndex())) {//如果是通用物料，则得到对应数量的
					//如果本行没有生成过id,需要为本行设置id
					if(!rowIndexIdMap.containsKey(reportBean.getTypeId())) {
						rowIndexIdMap.put(reportBean.getTypeId(), StringUtil.getUUID());
					}
					reportBean.setTypeId(rowIndexIdMap.get(reportBean.getTypeId()));
				}else {
					//如果本行没有生成过id,需要为本行设置id
					if(!rowIndexIdMap.containsKey(reportBean.getRowIndex())) {
						rowIndexIdMap.put(reportBean.getRowIndex(), StringUtil.getUUID());
					}
					reportBean.setTypeId(rowIndexIdMap.get(reportBean.getRowIndex()));
				}
			}else {
				reportBean.setTypeId(StringUtil.getUUID());
			}

			//工序设为不需要审核，则自动审核,交接出入库不自审核
			if (processBean.getIsNeedReviewed()==0 && !processBean.getProcessName().equals("交接入库") && !processBean.getProcessName().equals("交接出库")){
				reportBean.setStatus(1);
				reportBean.setApprovalReason("工序不需要审核，自动审核");
			}
		}
		//设置真正的报工人
		MyUser myUser=new MyUser();
		myUser.setUserId(list.get(0).getTouchPeople());
		myUser=userService.getUserByUserId(myUser);
		//如果工序是交接入库
		if(processBean.getProcessName().equals("交接入库")) {
			if(!ReturnStringUtil.REPORT_NOT_CHECKING_AUTO_IN.equals(myUserr.getIsUpdate())) {
				MyUser myUser3 =myUser;
				shoppingMallService.createNewTransaction((o)->{this.autoHandover(list,myUser3); return o;}, null);
				//校验一个物料类型只能在一个车间交接入库
				this.checkMaterialTypeOnlyOneWorkshop(list);
			}else {
				myUserr.setIsUpdate(null);
			}
			for(ReportBean reportBean:list) {
				FeedingAndReportBean feedingAndReportBean=this.GetOrderSystemCount(reportBean.getOrderId(), reportBean.getMachining(), reportBean.getRowIndex(),reportBean.getMaterialCode());
				feedingAndReportBean.setFeddingCount(workshopMapper.getOrderCount(reportBean));//投料数
				if(null==mergeBean) {
					//如果公司设置报工不需要审核或者不可以超过投料数，需要校验投料数
					if(companyBean.getIsApprovalReport()==0  ||  companyBean.getIsCanPassReport()==0) {
						//如果报工数大于投料数减掉已交接入库数（还可入库数）
						if((reportBean.getQualified()+reportBean.getNoQualified())>(feedingAndReportBean.getFeddingCount()-feedingAndReportBean.getWorkShopCount()-feedingAndReportBean.getFinishCount()-feedingAndReportBean.getPutOutCount())) {
							throw new ServiceException(reportBean.getMachining()+":"+reportBean.getColor()+"已有:车间:"+feedingAndReportBean.getWorkShopCount()+"、外协:"+feedingAndReportBean.getPutOutCount()+"、成品:"+feedingAndReportBean.getFinishCount()+",在"+workShop+"车间最多还可入库或领料"+(feedingAndReportBean.getFeddingCount()-feedingAndReportBean.getWorkShopCount()-feedingAndReportBean.getFinishCount()-feedingAndReportBean.getPutOutCount())+"付");
						}
					}
				}else {
					throw new ServiceException("该车间已合并到"+workShop+"请选择此车间入库");
				}
			}
		}else{
			String approvalPersonStr=null;
			for(ReportBean reportBean:list) {
				//设置工序已报工数，入库数，投料数
				FeedingAndReportBean feedingAndReportBean=this.setFeedAndReportBean(mergeBean,reportBean,aleradyReportList,detailList,companyBean);
				if(feedingAndReportBean.getInCount()<=0) {
					String errorStr=reportBean.getMachining()+":"+reportBean.getColor()+"在"+workShop+"车间";
					if(companyBean.getIsApprovalReport()!=1) {
						Assert.isTrue(1==2,errorStr+"未入库");
					}else {
						List<ReportBean> notApprovalList=aleradyReportList.stream().filter(pp->"交接入库".equals(pp.getProcedurText()) && reportBean.getWorkShopName().equals(pp.getWorkShopName()) && pp.getMachining().equals(reportBean.getMachining()) && pp.getRowIndex().equals(reportBean.getRowIndex()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()) && 0==pp.getStatus()).collect(Collectors.toList());
						//如果有为未审核的数据，需要提示谁可以审核
						if(null!=notApprovalList && notApprovalList.size()>0) {
							//获取审核人信息
							approvalPersonStr=this.getApprovalPersonStr(reportBean,approvalPersonStr);
							Assert.isTrue(1==2,errorStr+"入库未审核,"+approvalPersonStr);
						}else {
							Assert.isTrue(1==2,errorStr+"未入库");
						}
					}
				}
				//如果公司设置报工不需要审核或者不可以超过投料数，需要校验投料数
				if(companyBean.getIsCanPassReport()==0 && !"交接出库".equals(processBean.getProcessName())) {
					Assert.isTrue(reportBean.getSum()<=feedingAndReportBean.getFeddingCount() - feedingAndReportBean.getReportCount(),reportBean.getMachining()+":"+reportBean.getColor()+"报工数不能大于投料数"+feedingAndReportBean.getFeddingCount()+"减已报工数" + feedingAndReportBean.getReportCount());
				}
				Assert.isTrue(feedingAndReportBean.getInCount()>=reportBean.getSum(),reportBean.getMachining()+":"+reportBean.getColor()+"报工数不能大于入库数"+feedingAndReportBean.getInCount());
				Assert.isTrue(feedingAndReportBean.getInCount()-feedingAndReportBean.getReportCount()-reportBean.getSum()>=0,reportBean.getMachining()+":"+reportBean.getColor()+"已报工"+feedingAndReportBean.getReportCount()+"个，最多还可报工"+(feedingAndReportBean.getInCount()-feedingAndReportBean.getReportCount())+"付");
				//仓库类型 : 1成品仓 2报废仓 3待处理仓 4原材料仓 5 辅料仓 6半成品仓
				if("交接出库".equals(processBean.getProcessName())) {
					//如果是退回仓库
					if("仓库".equals(reportBean.getInWorkShop()) ||  "待处理仓".equals(reportBean.getInWorkShop())||"报废仓".equals(reportBean.getInWorkShop())) {
						reportBean.setDeviceId(wc.getProductionLine());
						int  warehouseType=4;
						reportBean.setOtherType(2);//交接到仓库
						if("报废仓".equals(reportBean.getInWorkShop())){
							warehouseType=2;
							reportBean.setOtherType(6);//交接到报废仓
						}else if("待处理仓".equals(reportBean.getInWorkShop())) {
							warehouseType=3;
							reportBean.setOtherType(5);//交接到待处理
						}
						WarehouseInOutDetailBean widb=this.reportToWarehouse(reportBean,dateString,warehouseType);
						inOutList.add(widb);
						reportBean.setOtherId(widb.getId());
					}else if ("外协".equals(reportBean.getInWorkShop())){//如果是外协
						reportBean.setOtherType(3);//交接到外协
						PutOutWarehouseBean putOutOrderBean=this.reportToPutOut(reportBean,dateString,wc);
						reportBean.setOtherId(putOutOrderBean.getId());
						putOutOrderList.add(putOutOrderBean);
					}else if("半成品仓".equals(reportBean.getInWorkShop())){
						//获取行号的记录
						String rowIndexOtherId=allMap.get(reportBean.getTypeId());
						//如果此行号没有保存过,并且行号不为-1
						if(null==rowIndexOtherId || "".equals(rowIndexOtherId)) {
							List<ReportBean> filterByTypeId=list.stream().filter(pp->pp.getTypeId().equals(reportBean.getTypeId())).collect(Collectors.toList());
							WarehouseInOutDetailBean widb=this.reportToHalfWarehouse(filterByTypeId, orderBean, myUser, reportBean);
							inOutList.add(widb);
							reportBean.setOtherId(widb.getId());
							allMap.put(reportBean.getTypeId(), reportBean.getOtherId());
						}else{
							reportBean.setOtherId(rowIndexOtherId);
						}
						reportBean.setOtherType(9);//交接到半成品
					}else if ("成品仓".equals(reportBean.getInWorkShop()) ) {
						isFinishWarehouse = 1;
						//获取行号的记录
						String rowIndexOtherId=allMap.get(reportBean.getTypeId());
						//如果此行号没有保存过,并且行号不为-1
						if(null==rowIndexOtherId || "".equals(rowIndexOtherId)) {
							WarehouseInOutDetailBean otherWarehouseBean=new WarehouseInOutDetailBean();
							otherWarehouseBean.setId(CreateIdUtil.getId(myUser.getCompany()+reportBean.getInWorkShop()));
							otherWarehouseBean.setCreateTime(dateString);
							otherWarehouseBean.setCreateUser(myUser.getUserId());
							otherWarehouseBean.setStatus(0);
							otherWarehouseBean.setCompany(myUser.getCompany());
							otherWarehouseBean.setRemark("车间交接至成品仓");
							otherWarehouseBean.setWorkShopId(reportBean.getWorkShopName());
							otherWarehouseBean.setDeptId(wc.getProductionLine());
							otherWarehouseBean.setInOutUnit(reportBean.getUnit());
							otherWarehouseBean.setRowIndex(reportBean.getRowIndex());
							otherWarehouseBean.setWarehouseType(1);
							otherWarehouseBean.setSource(1);
							otherWarehouseBean.setOrderId(reportBean.getOrderId());
							otherWarehouseBean.setCount((double) reportBean.getQualified());
							otherWarehouseBean.setNoCount((double) reportBean.getNoQualified());
							reportBean.setOtherId(otherWarehouseBean.getId());
							inOutList.add(otherWarehouseBean);
							allMap.put(reportBean.getTypeId(), reportBean.getOtherId());
						}else {
							reportBean.setOtherId(rowIndexOtherId);
						}
						reportBean.setOtherType(4);//交接到成品仓
					}else {
						Assert.isTrue(mergeBean==null,"该车间已合并到"+workShop+"请选择此车间出库");
						if(wcin==null) {
							wcin=basicDataService.getWCById(reportBean.getInWorkShop());
						}
						if(inProcessBean==null) {
							inProcessBean=basicDataService.getProcessByWorkShopId(wcin.getId());
						}
						ReportBean inReportBean=this.reportToOtherWorkShop(reportBean,sort,feedingAndReportBean,inProcessBean,companyBean);
						inList.add(inReportBean);
					}
				}
			}
		}
		String returnErrorStr="";
		formatter = new SimpleDateFormat("yyyy-MM-dd");
		day=formatter.format(new Date());
		workshopMapper.insertReport(list);
		//报工需要审核   发送审核提醒 并且工序需要审核并且报工记录不是已审核状态,并且不是交接出库
		if(companyBean.getIsApprovalReport()==1 && processBean.getIsNeedReviewed()==1 && list.get(0).getStatus() != 1 && !"交接出库".equals(processBean.getProcessName())) {
			//车间id   报工人   时间    内容
			returnErrorStr=this.sendWechatmsg("有新的报工数据，请尽快审核" ,"报工审核",wc,myUser,dateString ,wc.getWorkshopName()+"报工:"+weiXinNeiRong.toString(),1,RedirectUrlUtil.reportWork+"#userId="+list.get(0).getTouchPeople()+"&startTime="+day+"&endTime="+day+"&orderId="+list.get(0).getOrderId()+"&procedureId="+list.get(0).getProcedur(),processBean);
		}
		if(inList != null && inList.size()>0) {
			if(!ReturnStringUtil.REPORT_NOT_CHECKING_AUTO_IN.equals(myUserr.getIsUpdate())) {
				MyUser myUser3 =myUser;
				shoppingMallService.createNewTransaction((o)->{this.autoHandover(list,myUser3); return o;}, null);
			}else {
				myUserr.setIsUpdate(null);
			}
			workshopMapper.insertReport(inList);
			//报工需要审核   发送审核提醒
			if(companyBean.getIsApprovalReport()==1 && inList.get(0).getStatus()!=1) {
				returnErrorStr=this.sendWechatmsg("有新的报工数据，请尽快审核" ,"报工审核",wcin,myUser,dateString ,wc.getWorkshopName()+"报工："+weiXinNeiRong.toString(),1,RedirectUrlUtil.reportWork+"#userId="+inList.get(0).getTouchPeople()+"&startTime="+day+"&endTime="+day+"&orderId="+inList.get(0).getOrderId()+"&procedureId="+inList.get(0).getProcedur(),inProcessBean);
			}
		}
		if(inOutList!= null && inOutList.size()>0) {
			String idS="?ids=";
			for(WarehouseInOutDetailBean cc:inOutList) {
				idS=idS+cc.getId()+",";
			}
			idS=idS.substring(0, idS.length()-1);
			companyMaterialService.insertInOutRecode(inOutList);
			Map paramMap=new HashMap();
			paramMap.put("loginUserId", myUser.getUserId());
			paramMap.put("loginCompany", myUser.getCompany());
			paramMap.put("loginUserName", myUser.getUserName());
			String redirctUrl = RedirectUrlUtil.queryWarehouse;
			if(isFinishWarehouse == 1) {
				redirctUrl = RedirectUrlUtil.queryFinishWarehouse;
			}
			returnErrorStr=companyMaterialService.sendWechatMessage("有新的物料入库，请尽快审核", 2, weiXinNeiRong.toString(), dateString, paramMap, redirctUrl+idS, 1);
		}
		if(putOutOrderList!= null && putOutOrderList.size()>0) {
			putOutServiceNew.insertAllPutOutWarehouse(putOutOrderList);
			WorkshopProductionCycleBean dd=new WorkshopProductionCycleBean();
			dd.setId("-1");
			dd.setWorkshopName("外协");
			returnErrorStr=this.sendWechatmsg("有新的外协单，请尽快审核" ,"外协单审核",dd,myUser,dateString,wc.getWorkshopName()+"报工外协："+weiXinNeiRong.toString(),2,RedirectUrlUtil.waiXie,null);
		}
		return ReturnStringUtil.REPORT_SUCCESS+returnErrorStr;
	}

	/**
	 * 仅退回仓库报工
	 * @param list
	 * @param reportPerson
	 * @param myUserr
	 * @return
	 */
	private String reportOnlyReturnWarehouse(List<ReportBean> list, String reportPerson, MyUser myUserr) {
		SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateStr=sdFormat.format(new Date());
		List<WarehouseInOutDetailBean> warehouseInOutDetailBeans = new ArrayList<WarehouseInOutDetailBean>();
		if("".equals(reportPerson) || null == reportPerson ) {
			reportPerson=myUserr.getUserId();
		}
		//校验发料库存  已发数（已发数在报工记录表）-已退出 （已退数在出入库记录
		//物料发料记录
		List<ReportBean> materialReportRecord=reportMapper.getAleradyReportData(list.get(0).getOrderId());
		List<ReportBean> warehosueLis = reportMapper.getAleradyReturnData(list.get(0).getOrderId());
		List<ReportBean> isNoullList=materialReportRecord.stream().filter(pp->-1==pp.getOtherType()).collect(Collectors.toList());
		for(ReportBean reportBean:list) {
			//仓库发到车间条数
			double meterialInCount = isNoullList.stream().filter(pp->pp.getRowIndex().equals(reportBean.getRowIndex()) && pp.getMachining().equals(reportBean.getMachining()) && pp.getMaterialCode().equals(reportBean.getMaterialCode())).mapToDouble(ReportBean::getMaterialCount).sum();
			double materialOutCount =materialReportRecord.stream().filter(pp->pp.getRowIndex().equals(reportBean.getRowIndex()) && pp.getMachining().equals(reportBean.getMachining()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()) && pp.getOtherType() == 2).mapToDouble(ReportBean::getMaterialCount).sum();
			double aleradyReturnCount = warehosueLis.stream().mapToDouble(ReportBean::getMaterialCount).sum();
			Assert.isTrue(meterialInCount >= reportBean.getMaterialCount() + aleradyReturnCount + materialOutCount,"出库物料数不可大于:"+(meterialInCount - aleradyReturnCount -materialOutCount));
			reportBean.setCompany(myUserr.getCompany());//设置公司
			reportBean.setTouchPeople(reportPerson);//设置报工人
			//设置仓库数据

			WarehouseInOutDetailBean warehouseInOutDetailBean = this.reportToWarehouse(reportBean, dateStr, 4);
			warehouseInOutDetailBeans.add(warehouseInOutDetailBean);
		}

		//设置真正的报工人
		String  returnErrorStr="";
		MyUser myUser=new MyUser();
		myUser.setUserId(list.get(0).getTouchPeople());
		myUser=userService.getUserByUserId(myUser);
		if(warehouseInOutDetailBeans!= null && warehouseInOutDetailBeans.size()>0) {
			String idS="?ids=";
			for(WarehouseInOutDetailBean cc:warehouseInOutDetailBeans) {
				idS=idS+cc.getId()+",";
			}
			idS=idS.substring(0, idS.length()-1);
			companyMaterialService.insertInOutRecode(warehouseInOutDetailBeans);
			Map paramMap=new HashMap();
			paramMap.put("loginUserId", myUser.getUserId());
			paramMap.put("loginCompany", myUser.getCompany());
			paramMap.put("loginUserName", myUser.getUserName());
			returnErrorStr=companyMaterialService.sendWechatMessage("有新的物料入库，请尽快审核", 2, "物料从车间退回", dateStr, paramMap, RedirectUrlUtil.queryWarehouse+idS, 1);
		}
		System.out.println(warehouseInOutDetailBeans);
		return ReturnStringUtil.RETURN_SUCCESS+returnErrorStr;
	}

	/**
	 * 设备订单报工
	 * @param list
	 * @param reportPerson
	 * @param myUserr
	 * @return
	 */
	private String equipmentReport(ReportBean reportBean, String reportPerson, MyUser myUserr) {
		List<ReportBean> inList=new ArrayList<ReportBean>();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
		String day=formatter.format(new Date())+" 0:00:00";
		formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
		String dateString="";
		if(null==reportBean.getTouchTime() || "".equals(reportBean.getTouchTime())) {
			dateString= formatter.format(new Date());
		}else {
			dateString = reportBean.getTouchTime();
		}
		String tishi="未审批";
		//订单信息
		OrderBean orderBean=orderService.getOrderByOrderId(reportBean.getOrderId());
		WorkshopProductionCycleBean wc=basicDataService.getWCById(reportBean.getWorkShopName());
		WorkshopProductionCycleBean wcin=null;
		String workShop=wc.getWorkshopName();
		//获取车间合并情况
		MergeBean mergeBean=workshopMapper.getMerge(wc.getId());
		if(null!=mergeBean) {
			workShop=mergeBean.getMergeToWorkShop();
		}
		//工序信息
		ProcessBean processBean=basicDataService.getProcessById(reportBean.getProcedur());
		ProcessBean inProcessBean=null;
		//微信提醒信息  工序与工厂型号
		StringBuilder weiXinNeiRong=new StringBuilder("");
		weiXinNeiRong.append("工序名称:").append(processBean.getProcessName()).append("\n")
				.append("工厂型号:").append(orderBean.getFactoryId()).append("\n");
		Map map=new HashMap();
		map.put("loginCompany", myUserr.getCompany());
		//公司配置信息（主要报工是否需要审核）
		CompanyBean companyBean=companyService.getCompany(map);
		//整架map

		Map<String,String> allMap=new HashMap<String,String>();
		//获取该车间交接入库数(一开始是车间入库数减车间出库数)
//		long inCount=0;
		long sort=workshopMapper.getMaxSort()+1;
		//设置typeId
		Map<String,String> rowIndexIdMap=new HashMap<String,String>();
		//订单已经报过功的数据
		List<ReportBean> aleradyReportList=reportMapper.getAleradyReportData(reportBean.getOrderId());
		if(null==aleradyReportList) {
			aleradyReportList=new ArrayList<ReportBean>();
		}
		Integer aleradyReport=aleradyReportList.stream().filter(pp->pp.getProcedur().equals(reportBean.getProcedur())).mapToInt(ReportBean::getSum).sum();
		Assert.isTrue(aleradyReport+reportBean.getSum()<=orderBean.getFeedCount(),"已报工："+aleradyReport+",最多还可报："+orderBean.getFeedCount());
		//工序设为不需要审核，则自动审核,交接出入库不自审核
		if (processBean.getIsNeedReviewed()==0 && !processBean.getProcessName().equals("交接入库") && !processBean.getProcessName().equals("交接出库")){
			reportBean.setStatus(1);
			reportBean.setApprovalReason("工序不需要审核，自动审核");
		}
		reportBean.setTouchPeople(myUserr.getUserId());
		reportBean.setIsApprovalReport(companyBean.getIsApprovalReport());
		//如果是网页上报工将申报人设为制单人，制单人后传入
		if(!(reportPerson==null||reportPerson.equals(""))) {
			reportBean.setReportPeople(reportBean.getTouchPeople());
			reportBean.setTouchPeople(reportPerson);
		}
		reportBean.setSortKey(sort);
		reportBean.setTime(day);//设置日期时间
		reportBean.setCompany(myUserr.getCompany());
		reportBean.setTouchTime(dateString);
		reportBean.setTypeId(StringUtil.getUUID());
		MyUser myUser=new MyUser();
		myUser.setUserId(reportBean.getTouchPeople());
		myUser=userService.getUserByUserId(myUser);
		inList.add(reportBean);
		String returnErrorStr="";
		formatter = new SimpleDateFormat("yyyy-MM-dd");
		day=formatter.format(new Date());
		workshopMapper.insertReport(inList);
		//报工需要审核   发送审核提醒 并且工序需要审核并且报工记录不是已审核状态,并且不是交接出库
		if(companyBean.getIsApprovalReport()==1 && processBean.getIsNeedReviewed()==1 && reportBean.getStatus() != 1 && !"交接出库".equals(processBean.getProcessName())) {
			//车间id   报工人   时间    内容
			returnErrorStr=this.sendWechatmsg("有新的报工数据，请尽快审核" ,"报工审核",wc,myUser,dateString ,wc.getWorkshopName()+"报工:"+weiXinNeiRong.toString(),1,RedirectUrlUtil.reportWork+"#userId="+reportBean.getTouchPeople()+"&startTime="+day+"&endTime="+day+"&orderId="+reportBean+"&procedureId="+reportBean.getProcedur(),processBean);
		}
		return ReturnStringUtil.REPORT_SUCCESS+returnErrorStr;
	}

	/**
	 * 校验一个物料类型  只能在一个车间交接入库
	 * @param list
	 */
	private void checkMaterialTypeOnlyOneWorkshop(List<ReportBean> list) {
		ReportBean reportBean=list.get(0);
		//外协交接过来的不用管
		if(reportBean.getOtherType() != 8) {
			List<ReportBean> inList=workshopMapper.getOrderMaterialTypeInWorkShop(reportBean.getOrderId());
			inList=inList==null?new ArrayList<ReportBean>():inList;
			//根据物料类型分组
			Map<String,List<ReportBean>> materialMap=inList.stream().collect(Collectors.groupingBy(ReportBean::getMachining));
			for(ReportBean rr:list) {
				List<ReportBean> oneMaterialTypeInList=materialMap.get(rr.getMachining());
				if(oneMaterialTypeInList!=null && oneMaterialTypeInList.size()>0) {
					Set<String> inWorkShopIdSet=oneMaterialTypeInList.stream().map(ReportBean::getWorkShopId).collect(Collectors.toSet());
					Set<String> inWorkShopNameSet=oneMaterialTypeInList.stream().map(ReportBean::getWorkShopName).collect(Collectors.toSet());
					Assert.isTrue(inWorkShopIdSet.contains(reportBean.getWorkShopName()),"订单:"+rr.getOrderId()+rr.getMachining()+"只能在"+inWorkShopNameSet.toString()+"车间入库");
				}
			}
		}
	}

	/**
	 * @param myUser
	 * @param list
	 * @throws CloneNotSupportedException
	 * @throws ServiceException
	 *
	 */
	private void autoHandover(List<ReportBean> list, MyUser myUser) {
		ReportBean reportBean=list.get(0);
		Map map=new HashMap();
		map.put("loginCompany", myUser.getCompany());
		map.put("workShopId", reportBean.getWorkShopName());
		map.put("orderId", reportBean.getOrderId());
		List<FeedOrderDetailBean> feedList=issueNoteService.getWorkShopWarehouseMaterialDate(map);
		feedList=feedList==null?new ArrayList<FeedOrderDetailBean>():feedList;
		List<FeedOrderDetailBean> filterList=feedList.stream().filter(feed->feed.getReceiveCount()>0 && feed.getOrderId().equals(reportBean.getOrderId())).collect(Collectors.toList());
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String  auditorTime=simpleDateFormat.format(new Date());
		//如果还有没有领料的
		if(filterList.size()>0) {
			List<ReportBean> oneOrderList=new ArrayList<ReportBean>();
			filterList.forEach(feed->{
				String color=feed.getColor();
				if(null == color || "".equals(color)) {
					color=feed.getModal();
				}
				BigDecimal receiveCount=new BigDecimal(feed.getReceiveCount().toString());
				BigDecimal singleFeedCount =new BigDecimal(feed.getSingleFeedCount().toString());
				int qualitdCount =(int)receiveCount.divide(singleFeedCount).doubleValue();
				if(qualitdCount>0) {
					ReportBean report=new ReportBean();
					report.setId(feed.getId());
					report.setOrderId(reportBean.getOrderId());
					report.setWorkShopName(reportBean.getWorkShopName());
					report.setMaterialCode(feed.getMaterialCode());
					report.setRowIndex(feed.getLineNo());
					report.setColor(color);
					report.setMachining(feed.getMaterialType());
					report.setQualified(qualitdCount);
					report.setMaterialCount(receiveCount.doubleValue());
					report.setMaterialUnit(feed.getUnit());
					report.setStatus(1);
					report.setAuditor(myUser.getUserId());
					report.setAuditorTime(auditorTime);
					report.setApprovalReason("车间库存自动入库");
					oneOrderList.add(report);
				}
			});
			if(oneOrderList.size()>0) {
				issueNoteService.checkFeedOrderReceiveCount(oneOrderList);
				issueNoteService.checkWorkShopMaterialCount(oneOrderList,myUser);
				try {
					issueNoteService.insertReport(oneOrderList,myUser);
				} catch (ServiceException e) {
					e.printStackTrace();
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 *
	 * @param reportBean
	 * @return
	 */
	public  long  getOrderTurnoverCount(ReportBean reportBean) {
		return workshopMapper.getOrderTurnoverCount(reportBean);
	}


	/**
	 * 获取审核人提示字符串
	 * @param reportBean
	 * @param approvalPersonStr
	 * @return
	 */
	private String getApprovalPersonStr(ReportBean reportBean, String approvalPersonStr) {
		if(null!=approvalPersonStr) {
			return approvalPersonStr;
		}
		ProcessBean  pp=basicDataService.getProcessByWorkShopId(reportBean.getWorkShopName());
		Map<String,String> getApprovalMap=new HashMap<String,String>();
		getApprovalMap.put("processId", pp.getId());
		getApprovalMap.put("workShopId", reportBean.getWorkShopName());
		List<String> appList=workshopMapper.getCanApprovalReportUser(getApprovalMap);
		if(appList.size()<=0) {
			approvalPersonStr="   未设置审核人，去设置车间审核人员或者工序表页面设置";
		}else {
			approvalPersonStr="可审核人:"+appList.toString();
		}
		return approvalPersonStr;
	}

	/**
	 * 设置报工所需数据   投料数   入库数  已报功数
	 * @param mergeBean
	 * @param reportBean
	 * @param aleradyReportList
	 * @param detailList
	 * @param companyBean
	 * @return
	 */
	private FeedingAndReportBean setFeedAndReportBean(MergeBean mergeBean, ReportBean reportBean,
													  List<ReportBean> aleradyReportList, List<OrderInfoDetailBean> detailList, CompanyBean companyBean) {
		FeedingAndReportBean feedingAndReportBean =new FeedingAndReportBean();
		//投料数
		int feedCount=0;
		//报工数
		int reportCount=0;
		//入库数
		int inCount=0;
		//如果本车间没有被合并  入库数为本车间，同物料同行号，交接入库数
		String workShopId=reportBean.getWorkShopName();
		if(null!=mergeBean) {
			workShopId=mergeBean.getMergeToWorkShopId();
		}
		String workShopIdCopy=workShopId;
		//如果是没有电镀的
		if("".equals(reportBean.getAdditionalMaterialType())) {
			feedCount=detailList.stream().filter(dd->reportBean.getMachining().equals(dd.getMaterialType()) && reportBean.getRowIndex().equals(dd.getLineNo()))
					.mapToInt(OrderInfoDetailBean::getFeedingCount).sum();
			//本工序已报工数
			reportCount=aleradyReportList.stream().filter(pp->pp.getProcedur().equals(reportBean.getProcedur()) && pp.getMachining().equals(reportBean.getMachining()) && pp.getRowIndex().equals(reportBean.getRowIndex()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()) && "".equals(pp.getAdditionalMaterialType()))
					.mapToInt(ReportBean::getSum).sum();
			//如果公司需要报工需要审核，至获取审核过的数据
			if(companyBean.getIsApprovalReport()==1) {
				inCount=aleradyReportList.stream().filter(pp->1== pp.getStatus() && pp.getMachining().equals(reportBean.getMachining()) && pp.getRowIndex().equals(reportBean.getRowIndex()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()) && pp.getWorkShopName().equals(workShopIdCopy) && "交接入库".equals(pp.getProcedurText()) && "".equals(pp.getAdditionalMaterialType()))
						.mapToInt(ReportBean::getSum).sum();
				//如果工序不是交接出库，入库数为  入库数-出库数
//					if(!"交接出库".equals(reportBean.getProcedurText()) && !"交接至客户".equals(reportBean.getProcedurText())) {
//						inCount=inCount-aleradyReportList.stream().filter(pp->1== pp.getStatus() && pp.getMachining().equals(reportBean.getMachining()) && pp.getRowIndex().equals(reportBean.getRowIndex()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()) && pp.getWorkShopName().equals(workShopIdCopy) && ("交接出库".equals(pp.getProcedurText()) || "交接至客户".equals(pp.getProcedurText()))  && "".equals(pp.getAdditionalMaterialType()))
//								.mapToInt(ReportBean::getSum).sum();
//					}
			}else {//不需要审核无需判断否审核
				inCount=aleradyReportList.stream().filter(pp-> pp.getMachining().equals(reportBean.getMachining()) && pp.getRowIndex().equals(reportBean.getRowIndex()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()) && pp.getWorkShopName().equals(workShopIdCopy) && "交接入库".equals(pp.getProcedurText()) && "".equals(pp.getAdditionalMaterialType()))
						.mapToInt(ReportBean::getSum).sum();
				//如果工序不是交接出库，入库数为  入库数-出库数
//					if(!"交接出库".equals(reportBean.getProcedurText()) && !"交接至客户".equals(reportBean.getProcedurText())) {
//						inCount=inCount-aleradyReportList.stream().filter(pp-> pp.getMachining().equals(reportBean.getMachining()) && pp.getRowIndex().equals(reportBean.getRowIndex()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()) && pp.getWorkShopName().equals(workShopIdCopy) && ("交接出库".equals(pp.getProcedurText()) || "交接至客户".equals(pp.getProcedurText()))  && "".equals(pp.getAdditionalMaterialType()))
//								.mapToInt(ReportBean::getSum).sum();
//					}
			}
		}else {
			feedCount=detailList.stream().filter(dd->reportBean.getAdditionalMaterialType().equals(dd.getMaterialType()) && reportBean.getAdditionalRowIndex().equals(dd.getLineNo()))
					.mapToInt(OrderInfoDetailBean::getFeedingCount).sum();
			reportCount=aleradyReportList.stream().filter(pp->pp.getProcedur().equals(reportBean.getProcedur()) && pp.getAdditionalMaterialType().equals(reportBean.getAdditionalMaterialType()) && pp.getAdditionalRowIndex().equals(reportBean.getAdditionalRowIndex()) && pp.getMachining().equals(reportBean.getMachining()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()))
					.mapToInt(ReportBean::getSum).sum();
			//如果公司需要报工需要审核，至获取审核过的数据
			if(companyBean.getIsApprovalReport()==1) {
				inCount=aleradyReportList.stream().filter(pp->1== pp.getStatus() && pp.getAdditionalMaterialType().equals(reportBean.getAdditionalMaterialType()) && pp.getAdditionalRowIndex().equals(reportBean.getAdditionalRowIndex()) && pp.getWorkShopName().equals(workShopIdCopy) && "交接入库".equals(pp.getProcedurText()) && pp.getMachining().equals(reportBean.getMachining()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()))
						.mapToInt(ReportBean::getSum).sum();
				//如果工序不是交接出库，入库数为  入库数-出库数
//					if(!"交接出库".equals(reportBean.getProcedurText()) && !"交接至客户".equals(reportBean.getProcedurText())) {
//						inCount=inCount-aleradyReportList.stream().filter(pp->1== pp.getStatus() && pp.getAdditionalMaterialType().equals(reportBean.getAdditionalMaterialType()) && pp.getAdditionalRowIndex().equals(reportBean.getAdditionalRowIndex()) && pp.getWorkShopName().equals(workShopIdCopy) &&  ("交接出库".equals(pp.getProcedurText()) || "交接至客户".equals(pp.getProcedurText())) && pp.getMachining().equals(reportBean.getMachining()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()) )
//								.mapToInt(ReportBean::getSum).sum();
//					}
			}else {//不需要审核无需判断否审核
				inCount=aleradyReportList.stream().filter(pp-> pp.getAdditionalMaterialType().equals(reportBean.getAdditionalMaterialType()) && pp.getAdditionalRowIndex().equals(reportBean.getAdditionalRowIndex()) && pp.getWorkShopName().equals(workShopIdCopy) && "交接入库".equals(pp.getProcedurText()) && pp.getMachining().equals(reportBean.getMachining()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()))
						.mapToInt(ReportBean::getSum).sum();
				//如果工序不是交接出库，入库数为  入库数-出库数
//					if(!"交接出库".equals(reportBean.getProcedurText()) && !"交接至客户".equals(reportBean.getProcedurText())) {
//						inCount=inCount-aleradyReportList.stream().filter(pp-> pp.getAdditionalMaterialType().equals(reportBean.getAdditionalMaterialType()) && pp.getAdditionalRowIndex().equals(reportBean.getAdditionalRowIndex()) && pp.getWorkShopName().equals(workShopIdCopy) &&  ("交接出库".equals(pp.getProcedurText()) || "交接至客户".equals(pp.getProcedurText())) && pp.getMachining().equals(reportBean.getMachining()) && pp.getMaterialCode().equals(reportBean.getMaterialCode()))
//								.mapToInt(ReportBean::getSum).sum();
//					}
			}
		}
		if("款".equals(reportBean.getMachining())) {
			feedCount=1;
			inCount=1;
		}
		feedingAndReportBean.setFeddingCount(feedCount);//投料数
		feedingAndReportBean.setReportCount(reportCount);//已报工数
		feedingAndReportBean.setInCount(inCount);
		return feedingAndReportBean;
	}

//	public String insertReport(String reportArrayJSONStr,String reportPerson,MyUser myUser) throws ServiceException, CloneNotSupportedException {
//		JSONArray jsonArray = JSONArray.fromObject(reportArrayJSONStr);//把String转换为 数组
//		List<ReportBean> list= (List<ReportBean>)JSONArray.toCollection(jsonArray, ReportBean.class);
//		orderService.checkOrderIsFinish(list.get(0).getOrderId());
//		List<ReportBean> inList=new ArrayList<ReportBean>();
//		//仓库库记录
//		List<WarehouseInOutDetailBean> inOutList=new ArrayList<WarehouseInOutDetailBean>();
//		//外协记录
//		List<PutOutWarehouseBean> putOutOrderList=new ArrayList<PutOutWarehouseBean>();
//		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
//		String day=formatter.format(new Date())+" 0:00:00";
//		formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
//		String dateString = formatter.format(new Date());
//		String tishi="未审批";
//		//订单信息
//		OrderBean orderBean=orderService.getOrderByOrderId(list.get(0).getOrderId());
//		WorkshopProductionCycleBean wc=basicDataService.getWCById(list.get(0).getWorkShopName());
//		WorkshopProductionCycleBean wcin=null;
//		String workShop=wc.getWorkshopName();
//		//获取车间合并情况
//		MergeBean mergeBean=workshopMapper.getMerge(wc.getId());
//		//工序信息
//		ProcessBean processBean=basicDataService.getProcessById(list.get(0).getProcedur());
//		ProcessBean inProcessBean=null;
//		//微信提醒信息  工序与工厂型号
//		StringBuilder weiXinNeiRong=new StringBuilder("");
//		weiXinNeiRong.append("工序名称:").append(processBean.getProcessName()).append("\n")
//		.append("工厂型号:").append(orderBean.getFactoryId()).append("\n");
//		Map map=new HashMap();
//		map.put("loginCompany", myUser.getCompany());
//		//公司配置信息（主要报工是否需要审核）
//		CompanyBean companyBean=companyService.getCompany(map);
//		//整架map
//
//		Map<String,String> allMap=new HashMap<String,String>();
//		//获取该车间交接入库数(一开始是车间入库数减车间出库数)
//		long inCount=0;
//		long sort=workshopMapper.getMaxSort()+1;
//
//		//设置typeId
//		Map<String,String> rowIndexIdMap=new HashMap<String,String>();
//
//		//按行号倒序排序
//		Collections.sort(list, Comparator.comparing(ReportBean::getRowIndex).reversed());
//
//		for(ReportBean reportBean:list) {
//			if(reportBean.getQualified()+reportBean.getNoQualified()<=0) {
//				throw new ServiceException("合格数加不合格数必须大于0");
//			}
//			//微信消息提醒微信颜色，合格数，不合格数
//			weiXinNeiRong.append("物料:").append(reportBean.getMachining()).append("\n")
//			.append("颜色:").append(reportBean.getColor()).append("\n")
//			.append("合格数:").append(reportBean.getQualified()).append("\n")
//			.append("不合格数:").append(reportBean.getNoQualifiedReason()==null?0:reportBean.getNoQualifiedReason()).append("\n");
//			reportBean.setTouchPeople(myUser.getUserId());
//			reportBean.setIsApprovalReport(companyBean.getIsApprovalReport());
//			//如果是网页上报工将申报人设为制单人，制单人后传入
//			if(!(reportPerson==null||reportPerson.equals(""))) {
//				reportBean.setReportPeople(reportBean.getTouchPeople());
//				reportBean.setTouchPeople(reportPerson);
//			}
//			if(reportBean.getColor().equals("无")) {
//				throw new ServiceException("请先设置颜色");
//			}
//			reportBean.setSortKey(sort);
//			reportBean.setTime(day);//设置日期时间
//			reportBean.setCompany(myUser.getCompany());
//			reportBean.setTouchTime(dateString);
//			//如果不是单物料,设置组合id
//			if(reportBean.getMachingType()!=0) {
//				if("-1".equals(reportBean.getRowIndex())) {//如果是通用物料，则得到对应数量的
//					//如果本行没有生成过id,需要为本行设置id
//					if(!rowIndexIdMap.containsKey(reportBean.getTypeId())) {
//						rowIndexIdMap.put(reportBean.getTypeId(), StringUtil.getUUID());
//					}
//					reportBean.setTypeId(rowIndexIdMap.get(reportBean.getTypeId()));
//				}else {
//					//如果本行没有生成过id,需要为本行设置id
//					if(!rowIndexIdMap.containsKey(reportBean.getRowIndex())) {
//						rowIndexIdMap.put(reportBean.getRowIndex(), StringUtil.getUUID());
//					}
//					reportBean.setTypeId(rowIndexIdMap.get(reportBean.getRowIndex()));
//				}
//			}else {
//				reportBean.setTypeId(StringUtil.getUUID());
//			}
//
//
//			//工序设为不需要审核，则自动审核
//			if (processBean.getIsNeedReviewed()==0){
////				if (processBean.getIsNeedReviewed()==0 && !processBean.getProcessName().equals("交接入库") && !processBean.getProcessName().equals("交接出库")){
//				reportBean.setStatus(1);
//				reportBean.setApprovalReason("工序不需要审核，自动审核");
//			}
//		}
//		//设置真正的报工人
//		MyUser myUser2=new MyUser();
//		myUser2.setUserId(list.get(0).getTouchPeople());
//		myUser=userService.getUserByUserId(myUser2);
//		//如果工序是交接入库
//		if(processBean.getProcessName().equals("交接入库")) {
//			for(ReportBean reportBean:list) {
//				FeedingAndReportBean feedingAndReportBean=this.GetOrderSystemCount(reportBean.getOrderId(), reportBean.getMachining(), reportBean.getRowIndex());
//				feedingAndReportBean.setFeddingCount(workshopMapper.getOrderCount(reportBean));//投料数
//				if(null==mergeBean) {
//					//如果公司设置报工不需要审核或者不可以超过投料数，需要校验投料数
//					if(companyBean.getIsApprovalReport()==0  ||  companyBean.getIsCanPassReport()==0) {
//						//如果报工数大于投料数减掉已交接入库数（还可入库数）
//						if((reportBean.getQualified()+reportBean.getNoQualified())>(feedingAndReportBean.getFeddingCount()-feedingAndReportBean.getWorkShopCount()-feedingAndReportBean.getFinishCount()-feedingAndReportBean.getPutOutCount())) {
//							throw new ServiceException(reportBean.getMachining()+":"+reportBean.getColor()+"已有:车间:"+feedingAndReportBean.getWorkShopCount()+"、外协:"+feedingAndReportBean.getPutOutCount()+"、成品:"+feedingAndReportBean.getFinishCount()+",在"+workShop+"车间最多还可入库或领料"+(feedingAndReportBean.getFeddingCount()-feedingAndReportBean.getWorkShopCount()-feedingAndReportBean.getFinishCount()-feedingAndReportBean.getPutOutCount())+"付");
//						}
//					}
//				}else {
//					throw new ServiceException("该车间已合并到"+workShop+"请选择此车间入库");
//				}
//			}
//		}else if(processBean.getProcessName().equals("交接出库")){
//			for(ReportBean reportBean:list) {
//				FeedingAndReportBean feedingAndReportBean=new FeedingAndReportBean();
//				feedingAndReportBean.setFeddingCount(workshopMapper.getOrderCount(reportBean));//投料数
//				feedingAndReportBean.setReportCount(workshopMapper.getOrderOutCount(reportBean));//已报工数
//				if(null==mergeBean) {
//					reportBean.setType(2);
//					inCount=workshopMapper.getOrderTurnoverCount(reportBean);
//				}else {
//					workShop=mergeBean.getMergeToWorkShop();
//					ReportBean reb=reportBean.clone();
//					reb.setWorkShopName(mergeBean.getMergeToWorkShopId());
//					reb.setType(2);
//					inCount=workshopMapper.getOrderTurnoverCount(reb);
//				}
////    			int
//				//如果公司设置不需要审批
//				if (reportBean.getIsApprovalReport()!=1) {
//					tishi="未入库";
//				}else if(inCount<=0){//如果需要审批，并且没有实际库存
//					ReportBean reportBean2=reportBean.clone();
//					reportBean2.setIsApprovalReport(2);//设置查询入库数不分审核不审核
//					long inCountNoApproval=workshopMapper.getOrderTurnoverCount(reportBean2);
//					if(inCountNoApproval<=0) {
//						tishi="未入库";
//					}else {
//						tishi="入库未审核,";
//						ProcessBean  pp=basicDataService.getProcessByWorkShopId(reportBean.getWorkShopName());
//						Map<String,String> getApprovalMap=new HashMap<String,String>();
//						getApprovalMap.put("processId", pp.getId());
//						getApprovalMap.put("workShopId", reportBean.getWorkShopName());
//						List<String> appList=workshopMapper.getCanApprovalReportUser(getApprovalMap);
//						if(appList.size()<=0) {
//							tishi=tishi+"   未设置审核人，去设置车间审核人员或者工序表页面设置";
//						}else {
//							tishi=tishi+"可审核人:";
//							for(String str:appList) {
//								tishi=tishi+" "+str;
//							}
//						}
//					}
//				}
//				Assert.isTrue(inCount>0,reportBean.getMachining()+":"+reportBean.getColor()+"在"+workShop+"车间"+tishi);
//
//				//如果公司设置报工不需要审核或者不可以超过投料数，需要校验投料数
//				if(companyBean.getIsApprovalReport()==0  ||  companyBean.getIsCanPassReport()==0) {
//					Assert.isTrue((reportBean.getQualified()+reportBean.getNoQualified())<=feedingAndReportBean.getFeddingCount(),reportBean.getMachining()+":"+reportBean.getColor()+"报工数不能大于投料数"+feedingAndReportBean.getFeddingCount());
//				}
//				Assert.isTrue(inCount>=(reportBean.getQualified()+reportBean.getNoQualified()),reportBean.getMachining()+":"+reportBean.getColor()+"报工数不能大于入库数"+inCount);
//				Assert.isTrue(inCount-feedingAndReportBean.getReportCount()-reportBean.getQualified()-reportBean.getNoQualified()>=0,reportBean.getMachining()+":"+reportBean.getColor()+"已报工"+feedingAndReportBean.getReportCount()+"个，最多还可报工"+(inCount-feedingAndReportBean.getReportCount())+"付");
//				//仓库类型 : 1成品仓 2报废仓 3待处理仓 4原材料仓 5 辅料仓 6半成品仓
//				if("交接出库".equals(processBean.getProcessName())) {
//					//如果是退回仓库
//					if("仓库".equals(reportBean.getInWorkShop()) ||  "待处理仓".equals(reportBean.getInWorkShop())||"报废仓".equals(reportBean.getInWorkShop())) {
//						reportBean.setDeviceId(wc.getProductionLine());
//						int  warehouseType=4;
//						reportBean.setOtherType(2);//交接到仓库
//						if("报废仓".equals(reportBean.getInWorkShop())){
//							warehouseType=2;
//							reportBean.setOtherType(6);//交接到报废仓
//						}else if("待处理仓".equals(reportBean.getInWorkShop())) {
//							warehouseType=3;
//							reportBean.setOtherType(5);//交接到待处理
//						}
//						WarehouseInOutDetailBean widb=this.reportToWarehouse(reportBean,dateString,feedingAndReportBean,warehouseType);
//						inOutList.add(widb);
//						reportBean.setOtherId(widb.getId());
//					}else if ("外协".equals(reportBean.getInWorkShop())){//如果是外协
//						reportBean.setOtherType(3);//交接到外协
//						PutOutWarehouseBean putOutOrderBean=this.reportToPutOut(reportBean,dateString,wc);
//						reportBean.setOtherId(putOutOrderBean.getId());
//						putOutOrderList.add(putOutOrderBean);
//					}else if("半成品仓".equals(reportBean.getInWorkShop())){
//						//获取行号的记录
//						String rowIndexOtherId=allMap.get(reportBean.getTypeId());
//						//如果此行号没有保存过,并且行号不为-1
//						if(null==rowIndexOtherId || "".equals(rowIndexOtherId)) {
//							List<ReportBean> filterByTypeId=list.stream().filter(pp->pp.getTypeId().equals(reportBean.getTypeId())).collect(Collectors.toList());
//							WarehouseInOutDetailBean widb=this.reportToHalfWarehouse(filterByTypeId, orderBean, myUser, reportBean);
//							inOutList.add(widb);
//							reportBean.setOtherId(widb.getId());
//							allMap.put(reportBean.getTypeId(), reportBean.getOtherId());
//						}else{
//							reportBean.setOtherId(rowIndexOtherId);
//						}
//						reportBean.setOtherType(9);//交接到半成品
//					}else if ("成品仓".equals(reportBean.getInWorkShop()) ) {
//						//获取行号的记录
//						String rowIndexOtherId=allMap.get(reportBean.getTypeId());
//						//如果此行号没有保存过,并且行号不为-1
//						if(null==rowIndexOtherId || "".equals(rowIndexOtherId)) {
//							WarehouseInOutDetailBean otherWarehouseBean=new WarehouseInOutDetailBean();
//							otherWarehouseBean.setId(CreateIdUtil.getId(myUser.getCompany()+reportBean.getInWorkShop()));
//							otherWarehouseBean.setCreateTime(dateString);
//							otherWarehouseBean.setCreateUser(myUser.getUserId());
//							otherWarehouseBean.setStatus(0);
//							otherWarehouseBean.setCompany(myUser.getCompany());
//							otherWarehouseBean.setRemark("车间交接至成品仓");
//							otherWarehouseBean.setWorkShopId(reportBean.getWorkShopName());
//							otherWarehouseBean.setDeptId(wc.getProductionLine());
//							otherWarehouseBean.setInOutUnit(reportBean.getUnit());
//							otherWarehouseBean.setRowIndex(reportBean.getRowIndex());
//							otherWarehouseBean.setWarehouseType(1);
//							otherWarehouseBean.setSource(1);
//							otherWarehouseBean.setOrderId(reportBean.getOrderId());
//							otherWarehouseBean.setCount((double) reportBean.getQualified());
//							otherWarehouseBean.setNoCount((double) reportBean.getNoQualified());
//							reportBean.setOtherId(otherWarehouseBean.getId());
//							inOutList.add(otherWarehouseBean);
//							allMap.put(reportBean.getTypeId(), reportBean.getOtherId());
//						}else {
//							reportBean.setOtherId(rowIndexOtherId);
//						}
//						reportBean.setOtherType(4);//交接到成品仓
//					}else {
//						if(null==mergeBean) {
//							if(wcin==null) {
//								wcin=basicDataService.getWCById(reportBean.getInWorkShop());
//							}
//							if(inProcessBean==null) {
//								inProcessBean=basicDataService.getProcessByWorkShopId(wcin.getId());
//							}
//							ReportBean inReportBean=this.reportToOtherWorkShop(reportBean,sort,feedingAndReportBean,inProcessBean,companyBean);
//							inList.add(inReportBean);
//						}else {
//							throw new ServiceException("该车间已合并到"+workShop+"请选择此车间出库");
//						}
//					}
//				}
//			}
//		}else {
//			for(ReportBean reportBean:list) {
//				//如果公司设置报工不审核或者不能超过投料数，则不减出库数
//				if(companyBean.getIsApprovalReport()==0  ||  companyBean.getIsCanPassReport()==0) {
//					reportBean.setType(2);
//				}
//				if(null==mergeBean) {
//					inCount=workshopMapper.getOrderTurnoverCount(reportBean);
//				}else {
//					workShop=mergeBean.getMergeToWorkShop();
//					ReportBean reb=reportBean.clone();
//					reb.setWorkShopName(mergeBean.getMergeToWorkShopId());
//					inCount=workshopMapper.getOrderTurnoverCount(reb);
//				}
//				FeedingAndReportBean feedingAndReportBean=new FeedingAndReportBean();
//				feedingAndReportBean.setFeddingCount(workshopMapper.getOrderCount(reportBean));//投料数
//				if("款".equals(reportBean.getMachining())) {
//					feedingAndReportBean.setFeddingCount(1);
//					inCount=1;
//				}
//				feedingAndReportBean.setReportCount(workshopMapper.getReportCount(reportBean));//已报工数
//				if (reportBean.getIsApprovalReport()!=1) {
//					tishi="未入库";
//				}else if(inCount<=0){//如果需要审批，并且没有实际库存
//					ReportBean reportBean2=reportBean.clone();
//					reportBean2.setIsApprovalReport(2);//设置查询入库数不分审核不审核
//					long inCountNoApproval=workshopMapper.getOrderTurnoverCount(reportBean2);
//					if(inCountNoApproval<=0) {
//						tishi="未入库";
//					}else {
//						tishi="入库未审核,";
//						ProcessBean  pp=basicDataService.getProcessByWorkShopId(reportBean.getWorkShopName());
//						Map<String,String> getApprovalMap=new HashMap<String,String>();
//						getApprovalMap.put("processId", pp.getId());
//						getApprovalMap.put("workShopId", reportBean.getWorkShopName());
//						List<String> appList=workshopMapper.getCanApprovalReportUser(getApprovalMap);
//						if(appList.size()<=0) {
//							tishi=tishi+"   未设置审核人，去设置车间审核人员或者工序表页面设置";
//						}else {
//							tishi=tishi+"可审核人:";
//							for(String str:appList) {
//								tishi=tishi+" "+str;
//							}
//						}
//					}
//				}
//				Assert.isTrue(inCount>0,reportBean.getMachining()+":"+reportBean.getColor()+"在"+workShop+"车间"+tishi);
//				int maxReportCount=(int) inCount;
//				String tt="";
//				//如果公司设置报工不需要审核或者不可以超过投料数，需要校验投料数
//				if(companyBean.getIsApprovalReport()==0  ||  companyBean.getIsCanPassReport()==0) {
//					Assert.isTrue((reportBean.getQualified()+reportBean.getNoQualified())<=feedingAndReportBean.getFeddingCount(),reportBean.getMachining()+":"+reportBean.getColor()+"报工数不能大于投料数"+feedingAndReportBean.getFeddingCount());
//					maxReportCount=(int) (feedingAndReportBean.getFeddingCount()>inCount?inCount:feedingAndReportBean.getFeddingCount());
//					tt="或投料数";
//				}
//				Assert.isTrue(maxReportCount>=(reportBean.getQualified()+reportBean.getNoQualified()),reportBean.getMachining()+":"+reportBean.getColor()+"报工数不能大于入库数"+tt+inCount);
//				Assert.isTrue(maxReportCount-feedingAndReportBean.getReportCount()-reportBean.getQualified()-reportBean.getNoQualified()>=0,reportBean.getMachining()+":"+reportBean.getColor()+"已报工"+feedingAndReportBean.getReportCount()+"个，最多还可报工"+(maxReportCount-feedingAndReportBean.getReportCount())+"付");
//			}
//		}
//		String returnErrorStr="";
//		formatter = new SimpleDateFormat("yyyy-MM-dd");
//		day=formatter.format(new Date());
//		workshopMapper.insertReport(list);
//		//报工需要审核   发送审核提醒 并且工序需要审核并且报工记录不是已审核状态,并且不是交接出库
//		if(companyBean.getIsApprovalReport()==1 && processBean.getIsNeedReviewed()==1 && list.get(0).getStatus() != 1 && !"交接出库".equals(processBean.getProcessName())) {
//			//车间id   报工人   时间    内容
//			returnErrorStr=this.sendWechatmsg("有新的报工数据，请尽快审核" ,"报工审核",wc,myUser,dateString ,wc.getWorkshopName()+"报工:"+weiXinNeiRong.toString(),1,RedirectUrlUtil.reportWork+"#userId="+list.get(0).getTouchPeople()+"&startTime="+day+"&endTime="+day+"&orderId="+list.get(0).getOrderId()+"&procedureId="+list.get(0).getProcedur(),processBean);
//		}
//		if(inList != null && inList.size()>0) {
//			workshopMapper.insertReport(inList);
//			//报工需要审核   发送审核提醒
//			if(companyBean.getIsApprovalReport()==1 && inList.get(0).getStatus()!=1) {
//				returnErrorStr=this.sendWechatmsg("有新的报工数据，请尽快审核" ,"报工审核",wcin,myUser,dateString ,wc.getWorkshopName()+"报工："+weiXinNeiRong.toString(),1,RedirectUrlUtil.reportWork+"#userId="+inList.get(0).getTouchPeople()+"&startTime="+day+"&endTime="+day+"&orderId="+inList.get(0).getOrderId()+"&procedureId="+inList.get(0).getProcedur(),inProcessBean);
//			}
//		}
//		if(inOutList!= null && inOutList.size()>0) {
//			String idS="?ids=";
//			for(WarehouseInOutDetailBean cc:inOutList) {
//				idS=idS+cc.getId()+",";
//			}
//			idS=idS.substring(0, idS.length()-1);
//			companyMaterialService.insertInOutRecode(inOutList);
//			Map paramMap=new HashMap();
//			paramMap.put("loginUserId", myUser.getUserId());
//			paramMap.put("loginCompany", myUser.getCompany());
//			paramMap.put("loginUserName", myUser.getUserName());
//			returnErrorStr=companyMaterialService.sendWechatMessage("有新的物料入库，请尽快审核", 2, weiXinNeiRong.toString(), dateString, paramMap, RedirectUrlUtil.queryWarehouse+idS, 1);
//		}
//		if(putOutOrderList!= null && putOutOrderList.size()>0) {
//			putOutServiceNew.insertAllPutOutWarehouse(putOutOrderList);
//			WorkshopProductionCycleBean dd=new WorkshopProductionCycleBean();
//			dd.setId("-1");
//			dd.setWorkshopName("外协");
//			returnErrorStr=this.sendWechatmsg("有新的外协单，请尽快审核" ,"外协单审核",dd,myUser,dateString,wc.getWorkshopName()+"报工外协："+weiXinNeiRong.toString(),2,RedirectUrlUtil.waiXie,null);
//		}
////		if(otherWarehouseBeanList != null && otherWarehouseBeanList.size()>0) {
////			String idS="?ids=";
////			for(OtherWarehouseBean cc:otherWarehouseBeanList) {
////				idS=idS+cc.getId()+",";
////			}
////			idS=idS.substring(0, idS.length()-1);
////			otherWarehouseService.insertOtherWarehouseByList(otherWarehouseBeanList);
////			Map paramMap=new HashMap();
////			paramMap.put("loginUserId", myUser.getUserId());
////			paramMap.put("loginCompany", myUser.getCompany());
////			paramMap.put("loginUserName", myUser.getUserName());
////			returnErrorStr=companyMaterialService.sendWechatMessage("有新的物料入库，请尽快审核", 2, weiXinNeiRong.toString(), dateString, paramMap, RedirectUrlUtil.queryWarehouse+idS, 1);
////		}
//		return ReturnStringUtil.REPORT_SUCCESS+returnErrorStr;
//	}


	/**
	 * 报工出库到半成品仓
	 * @param list
	 * @return
	 */
	public  WarehouseInOutDetailBean reportToHalfWarehouse(List<ReportBean> list,OrderBean order,MyUser myUser,ReportBean reportBean) {
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		//校验物料存不存在
		Set<String> colorSets= list.stream().map(ReportBean::getColor).collect(Collectors.toSet());
		Set<String> materialTypeSet=list.stream().map(ReportBean::getMachining).collect(Collectors.toSet());
		TreeSet<String> colorSet=new TreeSet<>(colorSets);
		Map map=new HashMap<>();
		map.put("materialName", "半成品");
		map.put("model", order.getFactoryId());
		map.put("color", colorSet.toString());
		map.put("providerName", myUser.getCompany());
		map.put("loginCompany", myUser.getCompany());
		map.put("materialDeptId", order.getDeptId());
		List<CompanyMaterialTableBean> materialTableBeans=basicDataService.getUniqueCompanyMaterialByDetail(map);
		CompanyMaterialTableBean materialTableBean=new CompanyMaterialTableBean();
		if(materialTableBeans!=null && materialTableBeans.size()>0) {
			materialTableBean=materialTableBeans.get(0);
		}else {
			String materialCode=basicDataService.setCompanyMaterialCode(order.getFactoryId(), colorSet.toString());
			materialTableBean.setMaterialCode(materialCode);
			materialTableBean.setCompany(myUser.getCompany());
			materialTableBean.setMaterialName("半成品");
			materialTableBean.setModel(order.getFactoryId());
			materialTableBean.setColor(colorSet.toString());
			materialTableBean.setProviderName(myUser.getCompany());
			materialTableBean.setDefaultWarehouse("原材料仓");
			materialTableBean.setMaterialType("半成品");
			materialTableBean.setUnit("付");
			materialTableBean.setColorDescription(colorSet.toString());
			materialTableBean.setCreater(myUser.getUserName());
			materialTableBean.setCreationTime(simpleDateFormat.format(new Date()));
			materialTableBean.setIsEquals(1);
			materialTableBean.setMaterialDeptId(Integer.parseInt(order.getDeptId()));
			basicDataService.insertCompanyMaterial(materialTableBean);
			workshopMapper.insertMetrialCodeType(materialCode,materialTypeSet);
		}
		WarehouseInOutDetailBean widb=new WarehouseInOutDetailBean();
		Map materialMap=new HashMap<>();
		widb.setMaterialName(materialTableBean.getMaterialName());
		widb.setColor(materialTableBean.getColor());
		widb.setProviderName(materialTableBean.getProviderName());
		widb.setModel(materialTableBean.getModel());
		widb.setId(CreateIdUtil.getId(CreateIdUtil.WAREHOUSE_IN));
		widb.setMaterialType("半成品");
		widb.setRowIndex(reportBean.getRowIndex());
		widb.setDeptId(reportBean.getDeviceId());//设备id暂存为部门id
		widb.setMaterialCode(materialTableBean.getMaterialCode());
		widb.setOrderId(order.getOrderId());
		widb.setCreateUser(myUser.getUserId());
		widb.setCreateTime(simpleDateFormat.format(new Date()));
		widb.setStatus(0);
		widb.setCompany(myUser.getCompany());
		widb.setWorkShopId(reportBean.getWorkShopName());
		widb.setInOutUnit("付");
		widb.setRemark("车间交接至半成品仓");
		widb.setSource(1);
		widb.setWarehouseType(6);
		widb.setRemark("车间交接出库至半成品仓");
		widb.setType(7);
		double count=reportBean.getQualified();
		double noCount=reportBean.getNoQualified();
		widb.setCount(Math.floor(count));
		widb.setNoCount(Math.floor(noCount));
		return widb;
	}



	/**
	 * 获取最大的排序号
	 * @return
	 */
	public long getSort() {
		return workshopMapper.getMaxSort()+1;
	}


	/**
	 * 插入报工数据
	 */
	public void insertReport(List<ReportBean> list) {
		workshopMapper.insertReport(list);
	}



	/**
	 * 车间出库到其他车间
	 * @param reportBean
	 * @param sort
	 * @param feedingAndReportBean
	 * @param process
	 * @param companyBean
	 * @return
	 * @throws CloneNotSupportedException
	 */
	private ReportBean reportToOtherWorkShop(ReportBean reportBean, long sort,FeedingAndReportBean feedingAndReportBean, ProcessBean process, CompanyBean companyBean) throws CloneNotSupportedException {
		ReportBean inReportBean =new ReportBean();
		if(reportBean.getInWorkShop()==null||reportBean.getInWorkShop().equals("")) {
			throw new ServiceException("没有获取到接收车间");
		}
		if(reportBean.getWorkShopName().equals(reportBean.getInWorkShop())) {
			throw new ServiceException("出入库车间不能相同");
		}
		reportBean.setOtherType(1);//类型为普通的交接出库
		reportBean.setOtherId(StringUtil.getUUID());
		//克隆报工bean
		inReportBean=reportBean.clone();
		inReportBean.setWorkShopName(inReportBean.getInWorkShop());
		WorkshopProductionCycleBean wcin = basicDataService.getWCById(inReportBean.getWorkShopName());
		//如果接收数大于投料数
		MergeBean inmergeBean = workshopMapper.getMerge(inReportBean.getWorkShopName());
		if(null!=inmergeBean)
			Assert.isTrue(null==inmergeBean,wcin.getWorkshopName()+"车间已合并到"+inmergeBean.getMergeToWorkShop()+"请选择此车间交接");
		Assert.isTrue(process!=null,wcin.getWorkshopName()+"没有设置交接入库工序");
		inReportBean.setProcedur(process.getId());
		inReportBean.setSortKey(sort+1);
		return inReportBean;
//			inReportBean.setType(1);//是交接入库
//			//接收车间已接收数
//			long inCountTwo=workshopMapper.getOrderTurnoverCount(inReportBean);
//		    if(companyBean.getIsCanPassReport()==0 || companyBean.getIsApprovalReport()==0) {
//		    	if((inReportBean.getQualified()+inReportBean.getNoQualified())>(feedingAndReportBean.getFeddingCount()-inCountTwo)) {
//		    		throw new ServiceException(inReportBean.getColor()+"在"+wcin.getWorkshopName()+"车间已入库"+inCountTwo+"最多还可入库或领料"+(feedingAndReportBean.getFeddingCount()-inCountTwo)+"个");
//		    	}
//		    }
	}


	/**
	 * 车间交接到外协
	 * @param reportBean
	 * @param dateString
	 * @param wc
	 * @return
	 */
	private PutOutWarehouseBean reportToPutOut(ReportBean reportBean, String dateString, WorkshopProductionCycleBean wc) {
		PutOutWarehouseBean putOutWarehouseBean=new PutOutWarehouseBean();
		putOutWarehouseBean.setCompany(reportBean.getCompany());
		putOutWarehouseBean.setCount(reportBean.getQualified());
		putOutWarehouseBean.setCreateUser(reportBean.getTouchPeople());
		putOutWarehouseBean.setId(StringUtil.getUUID());
		putOutWarehouseBean.setInOutType(1);//入库
		putOutWarehouseBean.setMaterialType(reportBean.getMachining());
		putOutWarehouseBean.setNoCount(reportBean.getNoQualified());
		putOutWarehouseBean.setOrderId(reportBean.getOrderId());
		putOutWarehouseBean.setRowIndex(reportBean.getRowIndex());
		putOutWarehouseBean.setSource(1);//来源于报工
		putOutWarehouseBean.setStatus(0);//未审核
		putOutWarehouseBean.setSourceName(wc.getWorkshopName());
		putOutWarehouseBean.setType(reportBean.getMachingType());
		putOutWarehouseBean.setTypeId(reportBean.getTypeId());
		putOutWarehouseBean.setMaterialCode(reportBean.getMaterialCode());
		return putOutWarehouseBean;
	}


	/**
	 * 报工交接到仓库
	 * @param reportBean
	 * @param dateString
	 * @param feedingAndReportBean
	 * @param warehouseType
	 * @return
	 */
	public WarehouseInOutDetailBean reportToWarehouse(ReportBean reportBean, String dateString, int warehouseType) {
		Assert.isTrue(!"".equals(reportBean.getMaterialCode()) && reportBean.getMaterialCode()!=null,"退回至仓库物料信息不全");
		WarehouseInOutDetailBean widb=new WarehouseInOutDetailBean();
		Map materialMap=new HashMap<>();
		materialMap.put("loginCompany", reportBean.getCompany());
		materialMap.put("materialCode", reportBean.getMaterialCode());
		List<CompanyMaterialTableBean> companyMaterialTableBeanList= companyMaterialService.getCompanyMaterialByMap(materialMap);
		Assert.isTrue(companyMaterialTableBeanList!=null && companyMaterialTableBeanList.size()>0,"退回物料不存在");
		CompanyMaterialTableBean companyMaterialTableBean=companyMaterialTableBeanList.get(0);
		widb.setMaterialName(companyMaterialTableBean.getMaterialName());
		widb.setColor(companyMaterialTableBean.getColor());
		widb.setProviderName(companyMaterialTableBean.getProviderName());
		widb.setModel(companyMaterialTableBean.getModel());
		widb.setId(CreateIdUtil.getId(CreateIdUtil.WAREHOUSE_IN));
		widb.setMaterialType(reportBean.getMachining());
		widb.setRowIndex(reportBean.getRowIndex());
		widb.setDeptId(reportBean.getDeviceId());//设备id暂存为部门id
		widb.setMaterialCode(reportBean.getMaterialCode());
		widb.setOrderId(reportBean.getOrderId());
		widb.setCreateUser(reportBean.getTouchPeople());
		widb.setCreateTime(dateString);
		widb.setStatus(0);
		widb.setCompany(reportBean.getCompany());
		widb.setWorkShopId(reportBean.getWorkShopName());
		widb.setInOutUnit(reportBean.getUnit());
		widb.setRemark("车间退回至仓库");
		if(warehouseType!=4) {
			widb.setSource(1);
		}
		widb.setWarehouseType(warehouseType);
		widb.setRemark("车间交接出库");
		if(warehouseType==4) {
			widb.setType(7);
		}
		double count=reportBean.getQualified();
		double noCount=reportBean.getNoQualified();
		//单位是不是付的物料单位，将报工数转换为物料数
		if(!"付".equals(reportBean.getUnit())) {
			widb.setCount(reportBean.getMaterialCount());
			widb.setNoCount(0.0);
		}else{
			widb.setCount(Math.floor(count));
			widb.setNoCount(Math.floor(noCount));
		}
		return widb;
	}

	/**
	 * @param title
	 * @param type
	 * @param wc
	 * @param myUser
	 * @param dateString
	 * @param neiRong
	 * @param processBean
	 * @param pageType(1 我的报工页面 2报工审核页面  3 外协页面  4库存查询页面)
	 * @return
	 */
	public  String sendWechatmsg(String title, String type, WorkshopProductionCycleBean wc, MyUser myUser,
								 String dateString, String neiRong,int workShopType,String  pageType, ProcessBean processBean) {
		Map getApprovalMap=new HashMap();
		getApprovalMap.put("workShopId", wc.getId());
		getApprovalMap.put("type", workShopType);
		getApprovalMap.put("loginCompany", myUser.getCompany());
		List<String> userIds=basicDataService.getWorkShopApprovalReportUser(getApprovalMap);
		List<String> userIdList=new ArrayList<String>();
		if(processBean!=null && processBean.getIsNeedReviewed()==1) {
			userIdList=workshopMapper.getProcessSpprovelUserIdByProcessId(processBean.getId());
		}
		if(null != userIds) {
			userIdList.addAll(userIds);
		}

		if(null == userIdList || userIdList.size() <=0) {
			return "    友情提示："+wc.getWorkshopName()+"车间未设置报工审核人";
		}
		Map map=new HashMap();
		map.put("userIds", userIdList);
		List<String> openIdList=weiXinPeopleService.getOpenIdByUserIds(map);
		if(null == openIdList || openIdList.size()<=0) {
			return "    友情提示："+wc.getWorkshopName()+"车间审核人未关联微信，无法收到审核提醒，请人工通知审核！";
		}
		boolean bool=true;
		String accessToken=weiXinService.getAccessToken(null);
		for(String openId:openIdList) {
			JSONObject json=WeixinTemplateList.packJsonWatiApproval(title, type, myUser.getUserName(), myUser.getPhone(),dateString,neiRong , null, null, null, null, null, null, null, null);
			String xx=WeixinTemplateSender.sendWechatmsgToUser(openId, WeiXinParamesUtil.watiApprovalTemplateID, WeiXinParamesUtil.messageLink+"?loginToken="+openId+"&pageType="+pageType, json, accessToken);
			if(!"success".equals(xx)) {
				bool=false;
			}
		}
		if(!bool) {
			return "    友情提示："+wc.getWorkshopName()+"车间审核人或工序审核人未关注公众号，无法收到审核提醒，请人工通知审核！";
		}else {
			return "";
		}
	}

	public void insertLoginToken(String token,String userId) {
		workshopMapper.insertLoginToken(token,userId,"");
	}
	// 获取不合格原因
	public List<String> getNoReason(String workShopName, String produce) {
		return workshopMapper.getNoReason(workShopName,produce);
	}

	//整理周转量数据
	public List<Map> getTrunover(Map mapParam) throws ServiceException {
//		mapParam =this.workShopToId(mapParam);
		List<String> orderIdList=this.getWorkingOrder(mapParam);//获取正在生产的订单号
		if(orderIdList.size()<=0||null==orderIdList) {
			throw new ServiceException("该车间没有正在生产的"+mapParam.get("machining").toString()+"订单");
		}
		String workShopName=mapParam.get("workShop").toString();
		List<String> procedureList=this.getWorkingProcedureName(mapParam);//得到工序名称
		List<Map> ListMap=new ArrayList<Map>();
		//遍历正在生产的订单
		for(String orderId:orderIdList) {
			mapParam.put("orderId", orderId);
			//获取入库数
			long  inCount=workshopMapper.getInCount(mapParam);
			//获取合格数与不合格数
			List<TurnOverBea> turnList=workshopMapper.getTrunover(mapParam);
			OrderBean orderBean=orderService.getOrderByOrderId(orderId);
			//获取一个订单的周转量数据
			Map map=this.getOneOrderTurnover(procedureList,inCount,turnList);
			map.put("orderId", orderId);//订单编号
			map.put("factoryId", orderBean.getFactoryId());//工厂型号
			map.put("keHu", orderBean.getCustomerId());//客户型号
			map.put("keHuOrder", orderBean.getCustomerOrderId());//客户订单号
			ListMap.add(map);
		}
		if(ListMap.size()>0) {
			Map sumMap=this.getSumTurnover(procedureList,ListMap);
			ListMap.add(sumMap);
			Map<String,List<String>> procedureMap=new HashMap<String,List<String>>();
			procedureMap.put("procedureMap", procedureList);
			ListMap.add(procedureMap);
		}
		return ListMap;
	}

	//整理单个订单单个数据
	public Map getOneOrderTurnover(List<String> procedureList, long inCount, List<TurnOverBea> turnList) {
		Map map=new HashMap();
		//遍历工序名称
		for(String prcedure:procedureList) {
			//遍历订单数据
			for(TurnOverBea turnover:turnList) {
				//工序相同
				if(turnover.getProcedur().equals(prcedure)) {
					map.put(prcedure+"turnover", inCount-turnover.getHeGe());//工序未完成
					map.put(prcedure+"noQualified", turnover.getNoHeGe());//工序不合格
					map.put(prcedure+"lastTime", turnover.getLastTime());//最后报工时间
					break;
				}
			}
		}
		return map;
	}

	//整理合并数据
	public Map getSumTurnover(List<String> procedureList, List<Map> listMap) {
		Map map=new HashMap();
		map.put("orderId", "合计");//订单编号
		map.put("factoryId", "");//工厂型号
		map.put("keHu", "");//客户型号
		map.put("keHuOrder", "");//客户订单号
		for(String prcedure:procedureList) {
			long turnover=0;
			long noQualified=0;
			for(Map mapData:listMap) {
				turnover=turnover+Long.parseLong(mapData.get(prcedure+"turnover").toString());
				noQualified=noQualified+Long.parseLong(mapData.get(prcedure+"noQualified").toString());
			}
			map.put(prcedure+"turnover", turnover);//工序未完成
			map.put(prcedure+"noQualified", noQualified);//工序不合格
			map.put(prcedure+"lastTime", "");//最后报工时间
		}
		return map;
	}










	//获取正在生产的订单号
	private List<String> getWorkingOrder(Map map) {
		return workshopMapper.getWorkingOrder(map);
	}

	//获取每个车间周转量
	public List<TurnoverBean> getDeptTurnover(Map map) throws ServiceException {
		List<String> orderIdList=this.getWorkingOrder(map);//获取正在生产的订单号
		if(orderIdList.size()<=0||null==orderIdList) {
			throw new ServiceException("该车间没有正在生产"+map.get("machining").toString()+"的订单");
		}
		map.remove("machining");
		orderIdList=this.getWorkingOrder(map);
		map.put("orderIdList", orderIdList);
		return workshopMapper.getDeptTurnover(map);
	}

	//获取车间七日周转量
	public List<DeptReachBean> serverTurnover(Map map) {
		List<Integer> dayCounts=new ArrayList<Integer>();
		for(int i=-6 ;i<=0;i++) {
			dayCounts.add(i);
			map.put("dayCount", i);
		}
		map.put("dayCountList", dayCounts);
		List<DeptReachBean> list=workshopMapper.serverTurnover(map);
		return list;
	}

	//获取厂家名称
	public List<String> getFactory(String workShopName) {
		return workshopMapper.getFactory(workShopName);
	}

	//获取设备编号
	public List<String> getDeviceId(String workShopName) {
		return workshopMapper.getDeviceId(workShopName);
	}

	//获取设备名称
	public List<String> getDeviceName(String workShopName) {
		return workshopMapper.getDeviceName(workShopName);
	}

	//获取审核订单
	public List<ReportBean> getShenHeOrder(String userName) throws ServiceException {
		String[] userList=shenHeService.getButtomUser(userName, "工序审批");
		if(userList==null) {
			return null;
		}
		List<ReportBean> list=workshopMapper.getShenHeOrder(userList);
		return list;
	}

	//删除订单
//	public void deleteOder(String id) throws ServiceException {
//		ExceptionUtil.ifNull(id, "请选择订单");
//		String [] idList=id.split(",");
//		workshopMapper.deleteOder(idList);
//	}

	//审核订单
//	public void shenHeOrder(String userName, String id)throws ServiceException {
//		ExceptionUtil.ifNull(id, "请选择订单");
//		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//		String dateString = formatter.format(new Date());
//		String [] idList=id.split(",");
//		workshopMapper.shenHeOrder(idList,userName,dateString);
//
//	}

	//获取前十道不合格工序
	public List<DeptReachBean> getTopProcedureException(Map map) {
		return workshopMapper.getTopProcedureException(map);
	}

	//获取前十种不合格原因
	public List<DeptReachBean> getTopNoReasonException(Map map) {
		return workshopMapper.getTopNoReasonException(map);
	}

	//获取已报工合格数
	public long getqualified(ReportBean reportBean) {
		return workshopMapper.getqualifiedCount(reportBean);
	}

	//获取整厂周转量
	public List<ProductionExceptionBean> getFactoryTurnover(Map map) {
		return workshopMapper.getFactoryTurnover(map);
	}


	//获取未审批的报工数据
	public DatatablesViewPageBean getRoportNotApprovalData(Map map) {
		//可审核车间
		List<String> workShopList=basicDataService.getUserApprovalReportWorkShopByUserId(map.get("loginUserId").toString());
		//可审核工序
		List<String> processIdList=workshopMapper.getUserApprovelProcess(map);
		map.put("processIdList", processIdList);
		if(workShopList==null ||workShopList.size()<=0) {
			workShopList=new ArrayList<String>();
			workShopList.add("-1");
		}
		map.put("workShopList", workShopList);
		return this.getReportApprovalData(map);
	}


	//获取二审数据
	public DatatablesViewPageBean getSecondRoportApprovalData(Map map) {
		//本人可以审核的一审人
		List<String> secondApprovalUserList=approvalService.getApprovalIdByLoginId(map);
		if(secondApprovalUserList.size()<=0) {
			secondApprovalUserList.add("-1");
		}
		map.put("secondApprovalUserList", secondApprovalUserList);
		return this.getReportApprovalData(map);

	}
	//获取报工审核数据
	private DatatablesViewPageBean getReportApprovalData(Map map) {
		int count=0;
		DatatablesViewPageBean<ReportBean> dtcpb=new DatatablesViewPageBean<ReportBean>();
		count=workshopMapper.getRoportNotApprovalDataCount(map);
		List<String> typeIdList=workshopMapper.getRoportNotApprovalTypeId(map);
		if (typeIdList.size()<=0) {
			typeIdList.add("-1");
		}
		map.put("typeIdList", typeIdList);
		List<ReportBean> listReport=workshopMapper.getRoportNotApprovalData(map);
		listReport=this.setReportColor(listReport,map);
		dtcpb.setReturnData(listReport);
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	//获取本人报工数据
	public DatatablesViewPageBean getMyRoportData(Map map) {
		DatatablesViewPageBean<ReportBean> dtcpb=new DatatablesViewPageBean<ReportBean>();
		int count=workshopMapper.getMyRoportDataCount(map);
		List<String> typeIdList=workshopMapper.getMyRoportTypeId(map);
		map.put("typeIdList", typeIdList);
		List<ReportBean> listReport=workshopMapper.getMyRoportData(map);
		listReport=this.setReportColor(listReport,map);
		Map getApprovalMap=new HashMap<String,String>();
		for(ReportBean reportBean:listReport) {
			if(reportBean.getStatus()==0 || reportBean.getIsLaunch()==1) {
				//如果是交接入库，一定是本车间人员审核
				if("交接出库".equals(reportBean.getProcedur())) {
					switch(reportBean.getOtherType()) {
						case 2:
						case 4:
						case 5:
						case 6:
						case 9:
							map.put("type", 6);
							reportBean.setApprovalUserName(approvalService.getApprovalUserBeanByLoginUserId(map));
							break;
						case 1:
							if(reportBean.getFirstApprovalStatus()==1) {
								getApprovalMap.put("type", 8);
								getApprovalMap.put("loginUserId", reportBean.getFirstApprovalUser());
								getApprovalMap.put("loginCompany", map.get("loginCompany"));
								reportBean.setApprovalUserName(approvalService.getApprovalUserBeanByLoginUserId(getApprovalMap));
							}else {
								getApprovalMap.put("processId", reportBean.getRelationProcessId());
								getApprovalMap.put("workShopId", reportBean.getRelationWorkShopId());
								reportBean.setApprovalUserName(workshopMapper.getCanApprovalReportUser(getApprovalMap));
							}
							break;
						case 3:
						case 8:
							getApprovalMap.put("loginCompany", map.get("loginCompany"));
							reportBean.setApprovalUserName(this.getPutOutApprovalUserName(getApprovalMap));
							break;
					}
				}else {
					//如果二级审批已审批
					if(reportBean.getFirstApprovalStatus()==1) {
						getApprovalMap.put("type", 8);
						getApprovalMap.put("loginUserId", reportBean.getFirstApprovalUser());
						getApprovalMap.put("loginCompany", map.get("loginCompany"));
						reportBean.setApprovalUserName(approvalService.getApprovalUserBeanByLoginUserId(getApprovalMap));
					}else {
						getApprovalMap.put("processId", reportBean.getProcessId());
						getApprovalMap.put("workShopId", reportBean.getWorkShopId());
						reportBean.setApprovalUserName(workshopMapper.getCanApprovalReportUser(getApprovalMap));
					}
				}
			}
		}

		dtcpb.setReturnData(listReport);
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	/**
	 * 获取车间审核人
	 * @param map
	 * @return
	 */
	public List<String> getCanApprovalReportUser(Map map){
		return workshopMapper.getCanApprovalReportUser(map);
	}


	/**
	 * 获取外协审核人
	 * @param map
	 * @return
	 */
	public List<String> getPutOutApprovalUserName(Map map){
		return workshopMapper.getPutOutApprovalUserName(map);
	}

	/**
	 * 设置加工对象和颜色
	 * @param listReport
	 * @param loginCompany
	 * @return
	 */
	private List<ReportBean> setReportColor(List<ReportBean> listReport,Map map) {
		List<HalfMaterialBean> halfList=null;
		for(ReportBean reportBean:listReport) {
			if(reportBean.getType()!=0) {
				String machining="";
				StringBuilder colorSB=new StringBuilder();
				if(reportBean.getType()==-1) {
					machining="整架";
				}else {
					if(halfList==null) {
						halfList=structureTreeService.getHalfMaterialNameList(map);
					}
					for(HalfMaterialBean half:halfList) {
						if(Integer.parseInt(half.getId()) == reportBean.getType()) {
							machining=half.getHalfMaterialName();
							break;
						}
					}
				}

				for(MachingAndColorBean macb:reportBean.getMachingAndColorList()) {
					if(KUANG_TUI_SET.contains(macb.getMachining())) {
						colorSB.append(macb.getColor()).append("+");
					}
				}
				String color="";
				if(!"".equals(colorSB.toString())) {
					color=colorSB.toString().substring(0,colorSB.length()-1);
				}
				reportBean.setMachining(machining);
				reportBean.setColor(color);
			}else {
				String mm=reportBean.getMachingAndColorList().get(0).getMachining();
				if(!"".equals(reportBean.getMachingAndColorList().get(0).getAdditionalMaterialType())) {
					mm=mm+"-电镀-"+reportBean.getMachingAndColorList().get(0).getAdditionalColor();
				}
				reportBean.setMachining(mm);
				reportBean.setColor(reportBean.getMachingAndColorList().get(0).getColor());
			}
		}
		return listReport;
	}

	//获取制单人id
	public String getTouchPeople(String id) {
		return workshopMapper.getTouchPeople(id);
	}

	/**
	 * 通过typeId获取报工记录
	 * @param map
	 * @return
	 */
	public List<ReportBean> getReportByTypeId(String typeId){
		return workshopMapper.getReportByTypeId(typeId);
	}
	//报工审批
	public String approvalReport(Map map) {
		String ss="报工审批";
		List<ReportBean> list=workshopMapper.getReportByTypeId(map.get("id").toString());
		Assert.isTrue(null!=list && list.size()>0,"该报工记录不存在");
		Assert.isTrue(list.get(0).getStatus()==0 || (list.get(0).getStatus()==1 && list.get(0).getIsLaunch()==1),"只有未审核或已审核申请修改的记录可进行此操作");
		int status=Integer.parseInt(map.get("status").toString());
		CompanyBean companyBean = companyService.getCompany(map);
		//如果公司设置了，设置完成之后不允许报工，需要校验订单是否设置完成
		if(1!=companyBean.getAfterFinishIsCanReport()) {
			orderService.checkOrderIsFinish(list.get(0).getOrderId());
		}

		int bool=this.checkNeedSecondReport(list.get(0),status);
		//需要二次审核
		if(bool==1 || bool==2) {
			if(bool==1) {
				ss="不足订单数报工一审";
			}else {
				ss="超过投料数报工一审";
			}
			SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
			String dateString=simpleDateFormat.format(new Date());
			workshopMapper.firstApprovalReport(map);
			this.sendApprovalStatusMassage(status,list.get(0).getCreateUser(),map.get("loginUserName").toString(),ss,RedirectUrlUtil.myReportWork+"#typeId="+list.get(0).getTypeId());
			this.sendFirstApprovalMessage(status,map,list,RedirectUrlUtil.reportWork+"#userId="+list.get(0).getTouchPeople()+"&startTime="+dateString+"&endTime="+dateString+"&orderId="+list.get(0).getOrderId()+"&procedureId="+list.get(0).getProcedur()+"&isNeedSecondApptoval=1");
			return "";
		}else {//如果不需要二次审核
			//外协交接过来
			if(list.get(0).getOtherType()==8) {
				putOutServiceNew.approvalPutOutWarehouseByTypeId(list.get(0).getTypeId(),map);
			}
			ReportBean reportBean=list.get(0);
			//如果是车间发料  并且是退回，需要消除投料单领料数
			if(reportBean.getOtherType()==-2 && status == 2) {
				List<FeedOrderDetailBean> feedOrderDetailBeans=this.getFeedListByReport(reportBean);
				Assert.isTrue(null!=feedOrderDetailBeans && feedOrderDetailBeans.size()>0,"未找到自动发料投料单");
				FeedOrderDetailBean detailBean=feedOrderDetailBeans.get(0);
				BigDecimal aleradyReceiveCount=new BigDecimal(detailBean.getReceiveCount().toString());
				BigDecimal outCount=new BigDecimal(reportBean.getMaterialCount()+"");
				detailBean.setReceiveCount(aleradyReceiveCount.subtract(outCount).doubleValue());
				detailBean.setIsReceiveFinish(0);
				feedOrderDetailBeans.clear();
				feedOrderDetailBeans.add(detailBean);
				Map newMap=new HashMap();
				newMap.put("feedList", feedOrderDetailBeans);
				companyMaterialService.updateFeedOrderDetailReceive(newMap);
			}

			List<String> idList=new ArrayList<>();
			workshopMapper.approvalReport(map);

			if(list.get(0).getStatus()==1 && list.get(0).getIsLaunch()==1) {
				status=3;
				ss="报工退回申请审批";
			}
			return this.sendApprovalStatusMassage(status,list.get(0).getCreateUser(),map.get("loginUserName").toString(),ss,RedirectUrlUtil.myReportWork+"#typeId="+list.get(0).getTypeId());
		}
	}


	/**
	 * 发送一次审核消息专用
	 * @param status (状态  一般为审核)
	 * @param map (用户信息)
	 * @param list (报工消息集合)
	 * @param pageType (消息跳转页面)
	 * @return
	 */
	private String sendFirstApprovalMessage(int status, Map map, List<ReportBean> list,String pageType) {
		if(list.size()<=0) {
			return "";
		}
		map.put("type", 8);
		List<String> userIdList=approvalService.getApprovalUserIdByLoginUserId(map);
		if(null == userIdList || userIdList.size() <=0) {
			return "    友情提示：未设置您的报工二级审核人";
		}
		map.put("userIds", userIdList);
		List<String> openIdList=weiXinPeopleService.getOpenIdByUserIds(map);
		if(null == openIdList || openIdList.size()<=0) {
			return "    友情提示：二级审核人未关联微信，无法收到审核提醒，请人工通知审核！";
		}
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		String dateString=simpleDateFormat.format(new Date());
		StringBuilder neiRong=new StringBuilder("审核内容:\n");
		neiRong.append("订单编号:").append(list.get(0).getCompanyOrderId()).append("\n")
				.append("工厂型号:").append(list.get(0).getFactoryId()).append("\n");
		for(ReportBean report:list) {
			if("交接入库".equals(report.getProcedurText())) {
				neiRong.append("物料类型:").append(report.getMachining()).append("\n")
						.append("颜色:").append(report.getColor()).append("\n")
						.append("合格数:").append(report.getQualified().toString()).append("\n")
						.append("不合格数:").append(report.getNoQualified()).append("\n");
			}
		}
		boolean bool=true;
		String accessToken=weiXinService.getAccessToken(null);
		for(String openId:openIdList) {
			JSONObject json=WeixinTemplateList.packJsonWatiApproval("二级审核提醒", "报工审核", map.get("loginUserName").toString(), map.get("loginUserPhone").toString(),dateString,neiRong.toString() , null, null, null, null, null, null, null, null);
			String xx=WeixinTemplateSender.sendWechatmsgToUser(openId, WeiXinParamesUtil.watiApprovalTemplateID, WeiXinParamesUtil.messageLink+"?loginToken="+openId+"&pageType="+pageType, json, accessToken);
			if(!"success".equals(xx)) {
				bool=false;
			}
		}
		if(!bool) {
			return "    友情提示：二级审核人或工序审核人未关注公众号，无法收到审核提醒，请人工通知审核！";
		}else {
			return "审核成功";
		}

	}

	/**
	 * 校验是否需要二次审核
	 * 需要true  不需要返回false
	 * @param reportBean
	 * @return
	 */
	private int checkNeedSecondReport(ReportBean reportBean,int status) {
		int  bool=0;
		//如果是交接入库,并且是审核通过,并且没有经过一审
		if(reportBean.getProcedurText().equals("交接入库") && reportBean.getFirstApprovalStatus()!=1 && status==1) {
			FeedingAndReportBean ff=null;
			long  inCount=0;
			//如果公司设置报工不足订单数需要二次审核
			if (reportBean.getIsNeedSecondApproval()==1) {
				//入库数
				inCount=workshopMapper.getOrderTurnoverCount(reportBean);
				ff=workshopMapper.getOrderDetailCount(reportBean);
				//如果已入库数小于订单数
				if(inCount<ff.getOrderCount()) {
					bool=1;
				}
			}

			if(reportBean.getIsCanPassReport()==1) {
				if(inCount==0) {
					inCount=workshopMapper.getOrderTurnoverCount(reportBean);
				}
				if(ff==null) {
					ff=workshopMapper.getOrderDetailCount(reportBean);
				}
				if(inCount>ff.getFeddingCount()) {
					bool=2;
				}
			}

		}
		return bool;
	}

	/**
	 * 通过类型id获取一条报工记录
	 * @param typeId(类型id)
	 * @return
	 */
	private ReportBean getOneReportBeanByTypeId(String string) {
		List<ReportBean> list=workshopMapper.getReportByTypeId(string);
		Assert.isTrue(null!=list && list.size()>0,"该报工记录不存在");
		return list.get(0);
	}

	/**
	 *  审批批复通知
	 * @param status  审批结果
	 * @param touchPeople (被审核人，id)
	 * @param approval (审核人，姓名)
	 * @param remork (备注，审核类型)
	 * @param pageType(1 我的报工页面 2报工审核页面  3 外协页面  4库存查询页面)
	 */
	public  String sendApprovalStatusMassage(int status , String touchPeople, String approval, String remork , String pageType) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateStr=sdf.format(new Date());
		String  result="";
		if(status==1) {
			result="审核通过";
		}
		if(status==2) {
			result="退回";
		}
		if(status==3) {
			result="申请通过";
		}
		if(status==4) {
			result="申请被拒绝";
		}
		approval="审核人："+approval;
		List<String> openIdList=weiXinPeopleService.getOpenIdByUserId(touchPeople);
		if(null == openIdList || openIdList.size()<=0) {
			return "   友情提示：  被审核人未关联微信，无法收到审核结果提醒，请人工通知结果！";
		}
		String openId=openIdList.get(openIdList.size()-1);
		String accessToken=weiXinService.getAccessToken(null);
		JSONObject json=WeixinTemplateList.packJsonToApplyStatus("申请批复通知", result, approval, dateStr, remork, null, null, null, null, null);
		String xx=WeixinTemplateSender.sendWechatmsgToUser(openId, WeiXinParamesUtil.applyStatusTemplateID, WeiXinParamesUtil.messageLink+"?loginToken="+openId+"&pageType="+pageType, json, accessToken);
		if("success".equals(xx)) {
			return "";
		}else {
			return  "    友情提示：被审核人未关注微信公众号，无法收到审核结果，请人工通知结果！";
		}
	}

	//报工审批
	/**
	 * 通过其他id审核报工
	 * @param status（状态）
	 * @param loginUserId（审核人）
	 * @param time（审核时间）
	 * @param approvalReason（审核理由）
	 * @param otherId（其他id）
	 * @param map
	 */
	public void approvalReportByOtherId(Map map) {
		workshopMapper.approvalReport(map);
	}

	//批量审批
	public String approvalAllReport(Map map) {
		int status=Integer.parseInt(map.get("status").toString());
		Set<String> typeIdSet=new HashSet<String>();
		List<ReportBean> reportList=workshopMapper.getReportListById(map);
		Set<String> orderIdSet=reportList.stream().map(ReportBean::getOrderId).collect(Collectors.toSet());
		List<String> aleradyCheckTypeIdList=new ArrayList<String>();
		List<String> needSecondReportList=new ArrayList<String>();
		for(String orderId:orderIdSet) {
			orderService.checkOrderIsFinish(orderId);
		}
		for(ReportBean reportBean:reportList) {
			if(aleradyCheckTypeIdList.contains(reportBean.getTypeId())) {
				continue;
			}
			aleradyCheckTypeIdList.add(reportBean.getTypeId());
			Assert.isTrue(reportBean.getStatus()==0,reportBean.getOrderId()+"报工记录已审批或退回，不可再次操作");
			int bool=this.checkNeedSecondReport(reportBean,status);
			//不足数需要二次审核
			if(bool==1 || bool==2) {
				String tishi="";
				if(bool==1) {
					tishi="不足订单数报工一审";
				}else {
					tishi="超过投料数报工一审";
				}
				SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
				String dateString=simpleDateFormat.format(new Date());
				needSecondReportList.add(reportBean.getTypeId());
				List<ReportBean> list=reportList.stream().filter(rr->rr.getTypeId().equals(reportBean.getTypeId())).collect(Collectors.toList());
				this.sendApprovalStatusMassage(status,list.get(0).getCreateUser(),map.get("loginUserName").toString(),tishi,RedirectUrlUtil.myReportWork+"#typeId="+list.get(0).getTypeId());
				this.sendFirstApprovalMessage(status,map,list,RedirectUrlUtil.reportWork+"#userId="+list.get(0).getTouchPeople()+"&startTime="+dateString+"&endTime="+dateString+"&orderId="+list.get(0).getOrderId()+"&procedureId="+list.get(0).getProcedur()+"&isNeedSecondApptoval=1");
			}else {
				//外协交接过来
				if(reportBean.getOtherType()==8 && !typeIdSet.contains(reportBean.getTypeId())) {
					putOutServiceNew.approvalPutOutWarehouseByTypeId(reportBean.getTypeId(),map);
					typeIdSet.add(reportBean.getTypeId());
				}
				this.sendApprovalStatusMassage(status, reportBean.getCreateUser(), map.get("loginUserName").toString(), "报工审批",RedirectUrlUtil.myReportWork+"#typeId="+reportBean.getTypeId());
				//如果是车间发料  并且是退回，需要消除投料单领料数
				if(reportBean.getOtherType()==-2 && status == 2) {
					List<FeedOrderDetailBean> feedOrderDetailBeans=this.getFeedListByReport(reportBean);
					Assert.isTrue(null!=feedOrderDetailBeans && feedOrderDetailBeans.size()>0,"未找到自动发料投料单");
					FeedOrderDetailBean detailBean=feedOrderDetailBeans.get(0);
					BigDecimal aleradyReceiveCount=new BigDecimal(detailBean.getReceiveCount().toString());
					BigDecimal outCount=new BigDecimal(reportBean.getMaterialCount()+"");
					detailBean.setReceiveCount(aleradyReceiveCount.subtract(outCount).doubleValue());
					detailBean.setIsReceiveFinish(1);
					feedOrderDetailBeans.clear();
					feedOrderDetailBeans.add(detailBean);
					Map newMap=new HashMap();
					newMap.put("feedList", feedOrderDetailBeans);
					companyMaterialService.updateFeedOrderDetailReceive(newMap);
				}
			}
		}
		//如果没有需要二次审核的，直接审核
		if(needSecondReportList.size()<=0) {
			workshopMapper.approvalAllReport(map);
		}else {//如果有需要二次审核的，把需要二次审核的移除
			List<ReportBean> reportLists=(List<ReportBean>) map.get("reportList");
			map.put("reportList", reportLists.stream().filter(report->!needSecondReportList.contains(report.getTypeId())).collect(Collectors.toList()));
			map.put("secondReportList", reportLists.stream().filter(report->needSecondReportList.contains(report.getTypeId())).collect(Collectors.toList()));
			workshopMapper.approvalAllReport(map);
		}
		return "";
	}

	/**
	 * 通过报工记录获取投料单记录
	 * @param reportBean
	 * @return
	 */
	private List<FeedOrderDetailBean> getFeedListByReport(ReportBean reportBean) {
		Map<String,String> feedMap = new HashMap<String,String>();
		feedMap.put("loginCompany", reportBean.getCompany());
		feedMap.put("orderId", reportBean.getOrderId());
		FeedOrderMainBean mainBean=orderService.getFeedOrderMainByOrderId(feedMap);
		feedMap.put("materialType", reportBean.getMachining());
		feedMap.put("lineNo", reportBean.getRowIndex());
		feedMap.put("feedOrderId", mainBean.getId());
		feedMap.put("materialCode", reportBean.getMaterialCode());
		feedMap.put("useFactoryId", reportBean.getWorkShopName());
		feedMap.put("type", "1");
		feedMap.put("status", "1");
		return orderService.getFeedOrderDetailByDetail(feedMap);
	}

	//    删除报工
	public void deleteReport(Map map) {
		List<ReportBean> list=workshopMapper.getReportByTypeId(map.get("id").toString());
		Assert.isTrue(list != null && list.size() >0,"该记录不存在");
		ReportBean reportBean=list.get(0);
		Assert.isTrue(reportBean.getStatus()==2,"此报工记录未退回，不可删除");
//		if(reportBean.getOtherType()==1) {
//			List<String> otherList=list.stream().map(ReportBean::getTypeId).collect(Collectors.toList());
//			map.put("otherIdList", otherList);
//		}
		if(reportBean.getOtherType()==2 || reportBean.getOtherType()==4 || reportBean.getOtherType()==5 || reportBean.getOtherType()==6 || reportBean.getOtherType()==9) {
			List<WarehouseInOutDetailBean> xx=new ArrayList<WarehouseInOutDetailBean>();
			for(ReportBean rr:list) {
				WarehouseInOutDetailBean warehouseInOutDetailBean=new WarehouseInOutDetailBean();
				warehouseInOutDetailBean.setId(rr.getOtherId());
				xx.add(warehouseInOutDetailBean);
			}
			Map mm=new HashMap();
			mm.put("listIn", xx);
			companyMaterialService.deletePurchaseDetail(mm);
		}
		if(reportBean.getOtherType()==3  || reportBean.getOtherType()==8) {
			List<String> otherIdList=new ArrayList<String>();
			otherIdList.add(reportBean.getTypeId());
			putOutServiceNew.deletePutOutWarehouseByTypeIdList(otherIdList);
		}
//		if(reportBean.getOtherType()==4 || reportBean.getOtherType()==5 || reportBean.getOtherType()==6 || reportBean.getOtherType()==9) {
//			List<String> otherIdList=new ArrayList<String>();
//			otherIdList.add(reportBean.getOtherId());
//			otherWarehouseService.deleteOtherWarehouseByIdList(otherIdList);
//		}
//	    int
		workshopMapper.deleteReport(map);
	}

	//批量删除
	public void deleteAllReport(String idArray) {
		JSONArray jsonArray = JSONArray.fromObject(idArray);
		List<String> idList=jsonArray.subList(0, jsonArray.size());
		Map map=new HashMap();
		map.put("idList", idList);
		List<WarehouseInOutDetailBean> xx=new ArrayList<WarehouseInOutDetailBean>();
		List<ReportBean> reportList=workshopMapper.getReportListById(map);
		List<String> otherList=new ArrayList<String>();
		List<String> otherIdList=new ArrayList<String>();
//		List<String> otherWarehouseIdList=new ArrayList<String>();
		for(ReportBean reportBean:reportList) {
			Assert.isTrue(reportBean.getStatus()==0,reportBean.getOrderId()+"报工记录已审核或退回，不可删除");
			if(reportBean.getOtherType()==1) {
				otherList.add(reportBean.getOtherId());
			}
			if(reportBean.getOtherType()==2 || reportBean.getOtherType()==4 || reportBean.getOtherType()==5 || reportBean.getOtherType()==6 || reportBean.getOtherType()==9) {
				WarehouseInOutDetailBean warehouseInOutDetailBean=new WarehouseInOutDetailBean();
				warehouseInOutDetailBean.setId(reportBean.getOtherId());
				xx.add(warehouseInOutDetailBean);
			}
			if(reportBean.getOtherType()==3 || reportBean.getOtherType()==8) {
				otherIdList.add(reportBean.getTypeId());
			}
//			if(reportBean.getOtherType()==4 || reportBean.getOtherType()==5 || reportBean.getOtherType()==6) {
//				otherWarehouseIdList.add(reportBean.getOtherId());
//			}
		}
		map.put("otherIdList", otherList);
		workshopMapper.deleteAllReport(map);
		if(xx.size()>0) {
			Map mm=new HashMap();
			mm.put("listIn", xx);
			companyMaterialService.deletePurchaseDetail(mm);
		}
		if(otherIdList.size()>0) {
			putOutServiceNew.deletePutOutWarehouseByTypeIdList(otherIdList);
		}
//		if(otherWarehouseIdList.size()>0) {
//			otherWarehouseService.deleteOtherWarehouseByIdList(otherWarehouseIdList);
//		}
	}


	//获取车间报工加工对象
	public List<String> getMachining(Map map) {
		return workshopMapper.getMachining(map);
	}

	//查找某道工序是否报过工
	public List<String> findOrderProcedureRepoortRecore(Map map) {
		return workshopMapper.findOrderProcedureRepoortRecore(map);
	}

	//通过车间id获取加工对象
	public String geReportObjectByWorkShopId(String workshopName) {
		return workshopMapper.geReportObjectByWorkShopId(workshopName);
	}
	//获取物料周转量
	public DatatablesViewPageBean<MaterialTrunoverBean> getWorkShopMaterial(Map map) {
		DatatablesViewPageBean<MaterialTrunoverBean> dtcpb=new DatatablesViewPageBean<MaterialTrunoverBean>();
		int count=0;
		count=workshopMapper.getWorkShopMaterialCount(map);
		dtcpb.setReturnData(workshopMapper.getWorkShopMaterialData(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	//后去没有物料代码的物料周转量
	public DatatablesViewPageBean<MaterialTrunoverBean> getWorkShopMaterialNotCode(Map map) {
		DatatablesViewPageBean<MaterialTrunoverBean> dtcpb=new DatatablesViewPageBean<MaterialTrunoverBean>();
		int count=0;
		count=workshopMapper.getWorkShopMaterialNotCodeCount(map);
		dtcpb.setReturnData(workshopMapper.getWorkShopMaterialNotCodeDate(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	//获取车间物料总价
	public Double getWorkShopMaterialSumPrice(Map map) {
		return workshopMapper.getWorkShopMaterialSumPrice(map);
	}

	//通过其他id删除报工记录
	/**
	 * @param otherId
	 */
	public void deleteReportByOtherId(String otherId) {
		List<ReportBean> reportBeanList=this.getReportBeanByOtherId(otherId);
		for(ReportBean reportBean:reportBeanList) {
			Assert.isTrue(reportBean.getStatus()!=1,"对应的报工记录已审核，不可删除");
		}
		workshopMapper.deleteReportByOtherId(otherId);
	}

	/**
	 * 通过其他id获取报工数据
	 * @param otherId
	 * @return
	 */
	public List<ReportBean> getReportBeanByOtherId(String otherId) {
		return workshopMapper.getReportBeanByOtherId(otherId);
	}

	/**
	 * 新的获取周转量的方式
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<TurnoverBean> getTrunoverNew(Map map) {
		int count=0;
		DatatablesViewPageBean<TurnoverBean> dtcpb=new DatatablesViewPageBean<TurnoverBean>();
		map=this.setCompanyReportIsNeedApproval(map);
		count=workshopMapper.getTrunoverNewCount(map);
		dtcpb.setReturnData(workshopMapper.getTrunoverNew(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	/**
	 * 获取周转量明细
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<TurnoverBean> getTrunoverNewDetail(Map map) {
		int count=0;
		DatatablesViewPageBean<TurnoverBean> dtcpb=new DatatablesViewPageBean<TurnoverBean>();
		map=this.setCompanyReportIsNeedApproval(map);
		count=workshopMapper.getTrunoverNewDetailCount(map);
		dtcpb.setReturnData(workshopMapper.getTrunoverNewDetail(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	public List<TurnoverBean> getTrunoverNewList(Map map){
		return workshopMapper.getTrunoverNew(map);
	}

	/**
	 * 新的获取周转量的方式
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<TurnoverBean> getWorkLeftOver(Map map) {
		int count=0;
		DatatablesViewPageBean<TurnoverBean> dtcpb=new DatatablesViewPageBean<TurnoverBean>();
		count=workshopMapper.getWorkLeftOverCount(map);
		dtcpb.setReturnData(workshopMapper.getWorkLeftOver(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}


	/**
	 * 获取订单物料单位
	 * @param orderId(订单编号)
	 * @param machining(加工对象)
	 * @return
	 */
	public List<ReportBean> getMaterialUnit(Map map) {
		List<ReportBean> unitist=workshopMapper.getMaterialUnit(map);
		if(null==unitist) {
			unitist=new ArrayList<ReportBean>();
		}
		return unitist;
	}


	/**
	 * 获取报工公司数据
	 * @return
	 */
	public List<Map> getAllReportCompanyData(Map map) {
		return workshopMapper.getAllReportCompanyData(map);
	}


	/**
	 * 获取制单公司数据
	 * @param map
	 * @return
	 */
	public List<Map> getCreateOrderCompanyData(Map map) {
		return workshopMapper.getCreateOrderCompanyData(map);
	}

	/**
	 * 查询日产能详情
	 * @param workShopId(车间id)
	 * @param day(日期)
	 * @return
	 * @throws ServiceException
	 */
	public List<DutyBean> dayCapacityDetail(Map map) {
		return workshopMapper.dayCapacityDetail(map);
	}


	/**
	 * 申请修改报工
	 * @param id
	 * @param myUser
	 */
	public void launchUpdateReport(String id, MyUser myUser) {
		Assert.isTrue(id!=null && !"".equals(id),"未获取到id");
		ReportBean reportBean=this.getOneReportBeanByTypeId(id);
		orderService.checkOrderIsFinish(reportBean.getOrderId());
		Assert.notNull(reportBean,"此报工记录不存在");
		Assert.isTrue(reportBean.getStatus()==1,"此报工记录不是审核状态，不可申请退回");
		Assert.isTrue(reportBean.getIsLaunch()!=1,"此报工记录已经是申请退回状态");
		workshopMapper.launchUpdateReport(id,reportBean.getOtherId(),1);
		WorkshopProductionCycleBean wc=basicDataService.getWCById(reportBean.getWorkShopName());
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		String dateString=simpleDateFormat.format(new Date());
		ProcessBean processBean=basicDataService.getProcessById(reportBean.getProcedur());
		OrderBean orderBean=orderService.getOrderByOrderId(reportBean.getOrderId());
		String weiXinNeiRong="工序名称  ： "+processBean.getProcessName()+" 工厂型号： "+orderBean.getFactoryId()+"  颜色："+reportBean.getColor()+" 合格数："+reportBean.getQualified()+"  不合格数："+reportBean.getNoQualified();
		this.sendWechatmsg("有报工记录申请退回，请尽快审核" ,"报工退回申请",wc,myUser,dateString ,wc.getWorkshopName()+"申请退回内容:"+weiXinNeiRong.toString(),1,RedirectUrlUtil.reportWork+"#typeId="+reportBean.getTypeId(),processBean);
	}

	/**
	 * 拒绝修改申请
	 * @param id
	 */
	public void notLaunchReport(String id) {
		Assert.isTrue(id!=null && !"".equals(id),"未获取到id");
		ReportBean reportBean=this.getOneReportBeanByTypeId(id);
		orderService.checkOrderIsFinish(reportBean.getOrderId());
		Assert.notNull(reportBean,"此报工记录不存在");
		Assert.isTrue(reportBean.getIsLaunch()==1,"此报工记录不是修改退回状态");
		workshopMapper.launchUpdateReport(id,reportBean.getOtherId(),0);
		this.sendApprovalStatusMassage(4, reportBean.getCreateUser(), reportBean.getCompany(), "报工申请退回审批",RedirectUrlUtil.myReportWork+"#typeId="+reportBean.getTypeId());
	}


	/**
	 * 获取显示屏的异常数据
	 * @param deptId(部门id 非必传)
	 * @param workShopId(车间id 非必传)
	 * @param map
	 * @return
	 */
	public List<DisplayViewBean> getTrunoverDutyMantissa(Map map) {
		map=this.setCompanyReportIsNeedApproval(map);
		return workshopMapper.getTrunoverDutyMantissa(map);
	}



	/**
	 * 获取订单单行物料在系统所有地方(车间，外协，成品仓)的数量，不分审核未审核
	 * @param orderId(订单编号)
	 * @param maching(加工对象)
	 * @param rowIndex(行号)
	 * @return
	 */
	public   FeedingAndReportBean GetOrderSystemCount(String orderId,String maching,String rowIndex,String materialCode) {
		FeedingAndReportBean feedingAndReportBean=new FeedingAndReportBean();
		ReportBean reportBean=new ReportBean();
		reportBean.setOrderId(orderId);
		reportBean.setMachining(maching);
		reportBean.setRowIndex(rowIndex);
		reportBean.setMaterialCode(materialCode);
		feedingAndReportBean.setFinishCount(workshopMapper.getFinishCount(reportBean));//成品数量
		reportBean.setIsApprovalReport(3);//需要判断公司报工是否需要审核
		feedingAndReportBean.setWorkShopCount(workshopMapper.getOrderAllWorkShopTurnoverCount(reportBean));//获取车间数量，不管审核未审核
		PutOutWarehouseBean putOut=new PutOutWarehouseBean();
		putOut.setOrderId(orderId);
		putOut.setMaterialType(maching);
		putOut.setRowIndex(rowIndex);
		putOut.setMaterialCode(materialCode);
		feedingAndReportBean.setPutOutCount(putOutServiceNew.getPutOutWarehouseStockCount(putOut));
		return feedingAndReportBean;
	}


	/**
	 * 设置车间订单异常理由
	 * @param orderId(订单编号)
	 * @param workShopId(车间id)
	 * @param reason(拖期理由)
	 * @return
	 */
	public void setWorkShopOrderExceptionReason(Map map) {
		StringUtil.checkIsTrue(map, "orderId", "未获取到订单编号");
		StringUtil.checkIsTrue(map, "workShopId", "未获取到车间id");
		StringUtil.checkIsTrue(map, "reason", "未获取到异常理由");
		map.put("id", StringUtil.getUUID());
		map.put("type", "1");
		int  row=workshopMapper.setWorkShopOrderExceptionReason(map);
		Assert.isTrue(row>0,"设置失败");
	}

	/**
	 * 通过修改公司设置，将之前的报工记录全部审核
	 * @param map
	 */
	public void updateCompanySetToApprovalAllReport(Map map) {
		int  row=workshopMapper.updateCompanySetToApprovalAllReport(map);
//        Assert.isTrue(row>0,ReturnStringUtil.UPDATE_ERROR);
	}

}
